Skip to content

Commit f2268ae

Browse files
committed
add prob #1209; O(N) in time and O(N) in space;
1 parent 41d76e6 commit f2268ae

File tree

1 file changed

+89
-0
lines changed

1 file changed

+89
-0
lines changed
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
/*
2+
Given a string s, a k duplicate removal consists of choosing k adjacent and equal letters from s and removing them causing the left and the right side of the deleted substring to concatenate together.
3+
4+
We repeatedly make k duplicate removals on s until we no longer can.
5+
6+
Return the final string after all such duplicate removals have been made.
7+
8+
It is guaranteed that the answer is unique.
9+
10+
 
11+
12+
Example 1:
13+
14+
Input: s = "abcd", k = 2
15+
Output: "abcd"
16+
Explanation: There's nothing to delete.
17+
Example 2:
18+
19+
Input: s = "deeedbbcccbdaa", k = 3
20+
Output: "aa"
21+
Explanation:
22+
First delete "eee" and "ccc", get "ddbbbdaa"
23+
Then delete "bbb", get "dddaa"
24+
Finally delete "ddd", get "aa"
25+
Example 3:
26+
27+
Input: s = "pbbcggttciiippooaais", k = 2
28+
Output: "ps"
29+
 
30+
31+
Constraints:
32+
33+
1 <= s.length <= 10^5
34+
2 <= k <= 10^4
35+
s only contains lower case English letters.
36+
37+
来源:力扣(LeetCode)
38+
链接:https://leetcode-cn.com/problems/remove-all-adjacent-duplicates-in-string-ii
39+
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
40+
*/
41+
42+
/* O(N) in time and O(N) in space */
43+
#include <string>
44+
#include <stack>
45+
using namespace std;
46+
47+
class Solution {
48+
public:
49+
string removeDuplicates(string s, int k) {
50+
stack<char> a;
51+
stack<int> b;
52+
string res;
53+
54+
for(int i=0; i<(int)s.size(); ++i){
55+
if( (!a.empty())&&(a.top()==s[i]) ){
56+
if(b.top()==k-1){
57+
a.pop();
58+
b.pop();
59+
}
60+
else{
61+
int temp = b.top(); b.pop();
62+
b.push(temp+1);
63+
}
64+
}
65+
else{
66+
a.push(s[i]);
67+
b.push(1);
68+
}
69+
}
70+
71+
stack<char> a_r;
72+
stack<int> b_r;
73+
while(!a.empty()){
74+
a_r.push(a.top());
75+
b_r.push(b.top());
76+
a.pop();
77+
b.pop();
78+
}
79+
while(!a_r.empty()){
80+
for(int i=0; i<b_r.top(); ++i){
81+
res.push_back(a_r.top());
82+
}
83+
a_r.pop();
84+
b_r.pop();
85+
}
86+
87+
return res;
88+
}
89+
};

0 commit comments

Comments
 (0)