Super Reduced String

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