Super Reduced String

Sort by

recency

|

1713 Discussions

|

  • + 0 comments

    Here is my c++ solution, you can watch the explanation here : https://youtu.be/XgJKCkb1EjQ

    #include <bits/stdc++.h>
    
    using namespace std;
    
    int main()
    {
        string s;
        cin >> s;
        int i = 1;
        while(i < s.size()){
            if(s[i-1] == s[i]){
                s.erase(i-1, 2);
                if( i != 1) i--;
            }
            else i++;
        }
        if(s == "") s = "Empty String";
        cout << s;
        return 0;
    }
    
  • + 0 comments
    def superReducedString(s):
        ans=list(s)
        cha=1
        while cha==1:
            cha=0
            for i in range(len(ans)-1):
                if ans[i]==ans[i+1]:
                    ans[i]='0'
                    ans[i+1]='0'
            prev=ans[:]
            ans= [num for num in ans if num != '0']
            if prev!=ans:
                cha=1
        if ans ==[]:
            return 'Empty String'
        return ''.join(ans)
    
  • + 0 comments

    public static String superReducedString(String s) { char[] arr = s.toCharArray(); //Since String is immutable we can't directly alter the string so //use StringBuilder to store the altered String java.lang.StringBuilder sb = new java.lang.StringBuilder(); for(char c : arr){ if(sb.length()>0 &&(sb.charAt(sb.length()-1)==c)){ sb.deleteCharAt(sb.length()-1); }else{ sb.append(c); } } if(sb.length()==0){ return "Empty String"; } return sb.toString(); }

  • + 0 comments

    Python stack solution:

    def superReducedString(s):
        # Write your code here
        stk = []
        
        for c in s:
            stk.append(c)
            if len(stk) > 1 and stk[-1] == stk[-2]:
                stk.pop()
                stk.pop()
                
        return ''.join(stk) if len(stk) else "Empty String"
    
  • + 0 comments

    Solution using Stack in java:

     public static String superReducedString(String s) {
            String result = "";
            Stack<Character> stack = new Stack<>();
            int n = s.length();
            for(int i = 0; i < n; i++){
                char c = s.charAt(i);
                if(stack.empty() || c != stack.peek())
                    stack.push(c);
                else
                    stack.pop();
                }
            if(stack.empty())
                result = "Empty String";
            
            else
              for(char c: stack)
                  result += c;
            
            return result;        
            }