Super Reduced String

Sort by

recency

|

41 Discussions

|

  • + 0 comments

    Only three lines: Some practices in Hackerrank seem more difficult than easy and somes seem easier than intermediate.

    def superReducedString(s): # Write your code here

    for letter in s:
        s = s.replace(2*letter,"")
    
    return s if len(s) != 0 else "Empty String"
    
  • + 0 comments

    Java O(n)

    public static String superReducedString(String s) {
            Stack<Character> stack = new Stack<>();
            
            for (char c : s.toCharArray()) {
                if (!stack.isEmpty() && stack.peek() == c) {
                    stack.pop();
                } else {
                    stack.push(c);
                }
            }
            
            StringBuilder sb = new StringBuilder();
            for (char c : stack) {
                sb.append(c);
            }
            
            return sb.length() == 0 ? "Empty String" : sb.toString();
        }
    
  • + 0 comments
    def superReducedString(s):
        out = ''
        for value in s:
            if '' == out or value != out[-1]:
                out += value
            else:
                out = out[:-1]
        return out if '' != out else 'Empty String'
    
  • + 0 comments

    C++ 20:

    string onestepReduction (string s){
        int n = s.size();
        string reduced = "";
        int count;
        
        for (int i = 0; i < n-1; i++){
            if (s[i] != s[i+1]){
                reduced += s[i];
                count = i;
            }
            else{
                count = i+1;
                break;
            }
        }
        
        for (int j = count+1; j < n; j++) reduced += s[j];
        return reduced;
    }
    
    string superReducedString(string s) {
        string reduced = onestepReduction(s);
        
        while (reduced != s && reduced != ""){
            s = reduced;
            reduced = onestepReduction(s);
        }
        if (reduced == "") return "Empty String";
        else return reduced;
    }
    
  • + 0 comments

    using stack

    def superReducedString(s):
        # Write your code here
        s = [i for i in s]
        stack = []
        for i in s:
            if not stack:
                stack.append(i)
            else:
                if i==stack[-1]:
                    stack.pop(-1)
                else:
                    stack.append(i)
        if stack:
            return ''.join(stack)
        else:
            return 'Empty String'