Super Reduced String

Sort by

recency

|

1732 Discussions

|

  • + 0 comments
    def superReducedString(s):
        # Write your code here
        while re.search(r'([a-z])\1', s):
            s = re.sub(r'([a-z])\1', '', s)
        return 'Empty String' if len(s) == 0 else s
    
  • + 0 comments

    My simple C++ solution:

    string superReducedString(string &s) { int i = 0; for ( i = 1; ( !s.empty() && i <= s.size() ); i++) { if ( s[i-1] == s[i]) { s.erase((i - 1), 2); i = 0; } } return s = (!s.empty()) ? s: "Empty String"; }

  • + 0 comments

    The C# code solution:

    public static string superReducedString(string s) { List reduced = new List();

        foreach(char c in s)
        {
            if(reduced.Count>0 && reduced[reduced.Count -1] ==c)
            {
                reduced.RemoveAt(reduced.Count-1);
            }else{
                reduced.Add(c);
            }
        }
    
        if(reduced.Count==0) return "Empty String";
        else return new string(reduced.ToArray());
    
    }
    

    }

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