Super Reduced String

Sort by

recency

|

47 Discussions

|

  • + 0 comments

    Java 15

        public static String superReducedString(String s) {
            List<Character> chList = s.chars()
                                   .mapToObj(c -> (char) c) 
                                   .collect(Collectors.toList());
            int index = 0;
            while (index < chList.size() - 1) {
                if (chList.get(index).equals(chList.get(index + 1))) {
                    chList.remove(index); 
                    chList.remove(index);
                    if (index > 0) index--;
                } else index++;
            }
            
            String result = chList.stream()
                .map(e -> e.toString()).collect(Collectors.joining());
            return result.length() > 0 ? result : "Empty String";
        }
    
  • + 0 comments

    C++ Trick is to use a stack, but can just use a string the same way. Moving from left to right, if the current char is the same as on the top of stack (or .back() of string) pop it (pop_back()), and do not push it to stack, effectivly deleting them. Else we push character to the stack (push_back()). If we use a string as a stack, we can just return this resulting string;

  • + 0 comments

    def superReducedString(s): stack = [] for n in s: if not stack or stack[-1] != n: stack.append(n) else: stack.pop() if not stack: return 'Empty String' return "".join(stack)

  • + 0 comments

    !/bin/python3

    def superReducedString(s): # Write your code here stack = [] for char in s: if stack and stack[-1] == char: stack.pop() else: stack.append(char) reduced_string = ''.join(stack) return reduced_string if reduced_string else 'Empty String'

    if name == 'main': fptr = open(os.environ['OUTPUT_PATH'], 'w')

    s = input()
    
    result = superReducedString(s)
    
    fptr.write(result + '\n')
    
    fptr.close()
    
  • + 0 comments

    My answer in Python

    def superReducedString(s):
        print(s)
        pattern = r"(.)\1"
        
        while re.search(pattern, s):
            s = re.sub(pattern, "", s)
            print(s)
        
        if s:
            return s
        else:
            return "Empty String"