We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
- Prepare
- Algorithms
- Strings
- Super Reduced String
- Discussions
Super Reduced String
Super Reduced String
+ 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 C++ code solution
string superReducedString(string s) { string result; LOOP: string ns; ns.clear(); ns.shrink_to_fit(); bool flag = false; int i = 0; while(i < s.length()){ if (s[i] == s[i+1]){i= i + 2; flag = true;} else {ns.push_back(s[i]);i = i + 1; } } if (flag == true) {s.clear(); s.shrink_to_fit(); s = ns; goto LOOP;} if (ns.length() > 0){result = ns;} else {result = "Empty String";} return result; }
+ 0 comments Python
def super_reduced_string(s: str) -> str: for c in s: s = s.replace(c + c, "", 1) return s if s else "Empty String"
+ 0 comments I really enjoy solving this with Java 8 :
public static String superReducedString(String s) { // Write your code here StringBuffer sb = new StringBuffer(s); char p = '!'; int i = 0; while(i< sb.length()){ char c = sb.charAt(i); if(c==p){ sb.deleteCharAt(i); i--; sb.deleteCharAt(i); i--; p = '!'; if(i<0){ i=0; } }else{ p = c; i++; } } String res =sb.toString(); if(res.length()==0){ return "Empty String"; } return res; }
+ 0 comments def superReducedString(s): new_s = '' for i in range(len(s)): if not new_s: new_s += s[i] continue if new_s[-1]==s[i]: new_s = new_s[:-1] else: new_s += s[i] return new_s if new_s else 'Empty String'
Load more conversations
Sort 1594 Discussions, By:
Please Login in order to post a comment