Super Reduced String

Sort by

recency

|

1730 Discussions

|

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