Super Reduced String

Sort by

recency

|

1725 Discussions

|

  • + 0 comments

    Here is my c++ solution, you can watch the explanation here : https://youtu.be/XgJKCkb1EjQ

    #include <bits/stdc++.h>
    
    using namespace std;
    
    int main()
    {
        string s;
        cin >> s;
        int i = 1;
        while(i < s.size()){
            if(s[i-1] == s[i]){
                s.erase(i-1, 2);
                if( i != 1) i--;
            }
            else i++;
        }
        if(s == "") s = "Empty String";
        cout << s;
        return 0;
    }
    
  • + 0 comments

    def superReducedString(s): st=0 end=1 for i in range(len(s)): try: if(s[st]==s[end]): s=s[:st]+s[end+1:] st -= 1 end -= 1 st=max(st,0) end=max(end,1) print(s,st,end) else: st += 1 end += 1 except IndexError: return s if s else 'Empty String' return s

  • + 0 comments

    Best and performant approach in C++. Behold my simple C++ solution -

    string superReducedString(string s) {
        int i=1;
        while (i<s.length()) {
            if (s[i] == s[i-1]) {
                s.erase(i-1,2);
                i=1;
            } else {
                i++;
            }
        }
        
        if (s.empty()) {
            return "Empty String";
        } else {
            return s;
        }
    }
    
  • + 0 comments

    python recursive implementation

    def superReducedString(s):
        # Write your code here
        
        if len(s) == 0:
            return 'Empty String'
        elif len(s) == 1:
            return s
        elif all([s[i]!=s[j] for i, j in zip(range(len(s)-1),range(1, len(s)))]):
            return s
        else:
            for i, j in zip(range(len(s)-1),range(1, len(s))):
                if s[i]==s[j]:
                    s = s[:i] + s[j+1:]
                    return superReducedString(s)
    
  • + 0 comments

    RUST:

    fn superReducedString(s: &str) -> String {
        let mut last_idx = s.len() as i32;
        let mut result: Vec<&str> = s.split("").collect();
        let mut flag = true;
    
        while flag {
            flag = false;
            for n in 0..last_idx {
                if n <= last_idx {
                    let first = n as usize;
                    if result[first] == result[(n+1) as usize] {
                        result.remove(first);
                        result.remove(first);
                        last_idx -=2;
                        flag = true;
                    } 
                }   
            }
        }
        if !(result.join("").is_empty()) {
            return result.join("")
        }
        "Empty String".to_string()
    }