Super Reduced String

Sort by

recency

|

1741 Discussions

|

  • + 0 comments
    public static String superReducedString(String s) {
            // Write your code here
            String result = s;//s
            //Add while loop
            Pattern pattern = Pattern.compile("(.)\\1");//Two
            Matcher match = pattern.matcher(result);
            while(match.find()){
                //System.out.print(" ||initial_result --> "+ result);
                result = result.replaceAll("(.)\\1", "");
                //System.out.print(" final_result --> "+ result + " ||");
                match = pattern.matcher(result);
            }
            return !result.equals("") ? result : "Empty String";
        }
    
  • + 0 comments

    Simple Java solution:

        public static String superReducedString(String s) {
            StringBuilder sb = new StringBuilder(s);
            int index = 1;
            while (index < sb.length()) {
                if (sb.charAt(index) == sb.charAt(index - 1)) {
                    sb.delete(index - 1, index + 1);
                    index = Math.max(1, index - 1);
                } else index++;
            }
            return sb.length() > 0 ? sb.toString() : "Empty String";
        }
    
  • + 0 comments

    def superReducedString(s): stack = []

    for ch in s:
        if stack and stack[-1] == ch:
            stack.pop()
        else:
            stack.append(ch)
    
    return "".join(stack) if stack else "Empty String"    
    
  • + 0 comments
     public static String superReducedString(String s) {
        StringBuilder sb = new StringBuilder();
    
            for (int i = 0; i < s.length(); i++) {
                if (!(sb.length() == 0) && sb.charAt(sb.length() - 1) == s.charAt(i)) {
                    sb.deleteCharAt(sb.length() - 1);
                } else {
                    sb.append(s.charAt(i));
                }
            }
    
            return (sb.length() == 0) ? "Empty String" : sb.toString();
    
        }
    
  • + 0 comments

    Using stack : def superReducedString(s): st = [] for ch in s: if not st: st.append(ch) elif st and st[-1] == ch: st.pop() else: st.append(ch) return ''.join(st) if st else 'Empty String'