Skip to content

Commit e954d56

Browse files
Create remove_all_adjacent_from_string_ii.cpp
1 parent 67ab647 commit e954d56

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
class Solution {
2+
private:
3+
void removeHelper(string &s, int K) {
4+
int n = s.length();
5+
if(n < K ) return; // edgecase
6+
// cout<<"\nCurrent string - "<<s<<"\n";
7+
8+
bool remove = false;
9+
int position = 0;
10+
int start = 0;
11+
12+
while(position <= n-K+1) {
13+
if(s[position] == s[position+1]) { // if two characters match, then check for the next K characters
14+
start = position; // initialize start pointer for removal
15+
// cout<<"Start"<<start<<"\t";
16+
int checkEqual = 1; // to check for K matches, the count of equal matches must be K - 1. Thus, 1 + K - 1 = K.
17+
while(s[position] == s[position+1]) { // if all the next K characters match
18+
++position, ++checkEqual;
19+
if(checkEqual == K) break;
20+
}
21+
// cout<<"CheckEqual"<<checkEqual<<"\n";
22+
if(checkEqual == K and start <= n-K) {
23+
remove = true; // flag for recursive call
24+
s.erase(s.begin() + start, s.begin() + start + K);
25+
cout<<s<<" |##| "<<remove<<" | ";
26+
position += K;
27+
if(position == n) { // check for out of bounds
28+
// cout<<"1\n";
29+
break;
30+
}
31+
else
32+
// cout<<"0\n";
33+
}
34+
}
35+
else {
36+
++position; //increment and check next char in case of mismatch
37+
}
38+
}
39+
if(remove == false) return; //if no duplicate found or if string has become empty after recursive deletions
40+
else if(remove == true) removeHelper(s, K);
41+
}
42+
public:
43+
string removeDuplicates(string S, int k) {
44+
if(S == "") return "";
45+
removeHelper(S, k);
46+
return S;
47+
}
48+
};

0 commit comments

Comments
 (0)