给一个string s,如果s_i == s_i+1,移除这两个characters,得到一个新的string,重复这个过程,返回最终的string。比如,
"aabbccd" -> "d", "aabbac" -> "aaac" -> "ac"
Given a string "s", remove all sub strings with two consecutive chars.
"aabbccd" -> "d", "aabbac" -> "aaac" -> "ac"
Given a string "s", remove all sub strings with two consecutive chars.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | #include "misc.h" class Solution { public: string Remove(string s) { bool cont = true; while (cont) { cont = false; int i = 1, sz = s.size(); while(i<sz){ if(s[i]!=s[i-1]){ i++; }else{ int start = i-1; while(i<sz && s[i]==s[start]) i++; int len = i-start;//substring with same char cont = true; if(len%2==0){ s.erase(start, len); i -= len; }else{ s.erase(start, len-1); i -= (len-1);//i points to the first char after the removed string } } } } return s; } }; int main() { Solution sol; cout<<sol.Remove("aabbccd")<<endl; cout<<sol.Remove("eddegfsaabbccd")<<endl; return 0; } |