Super Reduced String

Sort by

recency

|

1729 Discussions

|

  • + 0 comments

    My Java 8 Solution

    public static String superReducedString(String s) {
            StringBuilder reducedString = new StringBuilder();
            
            for (char c : s.toCharArray()) {
                int length = reducedString.length();
                
                if (length > 0 && reducedString.charAt(length - 1) == c) {
                    reducedString.deleteCharAt(length - 1);
                } else {
                    reducedString.append(c);
                }
            }
            
            return reducedString.length() == 0 ? "Empty String" : reducedString.toString();
        }
    
  • + 0 comments
    public static String superReducedString(String str) {
        String reducedString = _superReducedString(str);
        while(hasAdjacent(reducedString) && !reducedString.equals("Empty String")) {
            reducedString = _superReducedString(reducedString); 
        }
        return reducedString;
    }
    
    private static String _superReducedString(String str) {
        if(str == null || str.trim().equals("")) return "Empty String";
        if(str.length() == 1) return str;
        if(!hasAdjacent(str)) return str;
    
        if(str.substring(0, 1).equals(str.substring(1, 2))) {
            return _superReducedString(str.substring(2));
        }
        String s = _superReducedString(str.substring(1));
        return str.substring(0, 1) + (s.equals("Empty String") ? "" : s);       
    }
    
    static boolean hasAdjacent(String str) {
        for(int i=0; i<str.length()-1; i++) {
            if(str.charAt(i) == str.charAt(i+1)) return true;
        }
        return false;
    }
    
  • + 0 comments

    here is a python solution with O(n) time and O(n) space in worse case; however, if the stack ends up being empty the space will be O(1)

    def superReducedString(s):
        stack = []
        
        for c in s:
            if not stack or stack[-1] != c:
                stack.append(c)
            else:
                stack.pop()
        
        if not stack:
            return "Empty String"
            
        return "".join(stack)
    
  • + 0 comments

    Here is problem solution in Python, Java, C++, C and javascript - https://programmingoneonone.com/hackerrank-super-reduced-string-problem-solution.html

  • + 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;
    }