Removing Stars From a String

Given a string s, which contains stars *.

In one operation, you can.

Choose a star in s.

Remove the closest non-star character to its left, as well as remove the star itself.

Return the string after all stars have been removed.

Note:

The input will be generated such that the operation is always possible.

It can be shown that the resulting string will always be unique.

For Example

Input: helll*o

Output: hello

Approach

Explanation:

We need to iterate the input string from start to end and do the below steps.

Step 1: If we encounter * at the ith position then we remove the last appended/added character from the resulting string.

Step 2: If we encounter another character then * then we append the current character into our resulting string.

Let's take one example

Input:: helll*o

res=""

i=0,ch=h, res="h"

i=1, ch=e, res="he",

i=2,ch=l,res="hel"

i=3,ch=l,res="hell"

i=4,ch=l,res="helll"

i=5,ch=*,res="hell"

i=6, ch=o, res="hello"

Java

public class RemoveStars {
    public static void main(String[] args) {
        {
            String input = "helll*o";
            System.out.println(removeStars(input));
        }

    }

    public static String removeStars(String s) {

        // create string builder to store the resulting
        // string
        StringBuilder str = new StringBuilder();

        // iterate through the whole string
        for (int i = 0; i < s.length(); i++) {
            // Case 1:: If current character is '*' then
            // remove from the resulting string if resulting string
            // size is greater then 0
            if (s.charAt(i) == '*') {
                if (str.length() > 0) {
                    str.deleteCharAt(str.length() - 1);
                }

            }
            // Case:: If current character is other then '*' then
            // append into the resulting string
            else {
                str.append(s.charAt(i));
            }
        }

        // return the final string
        return str.toString();

    }
}

C++

#include <bits/stdc++.h>
using namespace std;

string removeStars(string s)
{
    string res = "";
    for (int i = 0; i < s.size(); i++)
    {
        if (s[i] == '*')
        {
            if (res.size() > 0)
            {
                res.pop_back();
            }
        }
        else
        {
            res += s[i];
        }
    }
    return res;
}
int main()
{
    string str = "helll*o";
    cout << removeStars(str);
    return 0;
}


No comments:

Post a Comment