Skip to content

Commit 89df565

Browse files
committed
add prob #1047; O(N) in time and O(N) in space;
1 parent f1d9196 commit 89df565

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
/*
2+
Given a string S of lowercase letters, a duplicate removal consists of choosing two adjacent and equal letters, and removing them.
3+
4+
We repeatedly make duplicate removals on S until we no longer can.
5+
6+
Return the final string after all such duplicate removals have been made.  It is guaranteed the answer is unique.
7+
8+
 
9+
10+
Example 1:
11+
12+
Input: "abbaca"
13+
Output: "ca"
14+
Explanation:
15+
For example, in "abbaca" we could remove "bb" since the letters are adjacent and equal, and this is the only possible move.  The result of this move is that the string is "aaca", of which only "aa" is possible, so the final string is "ca".
16+
 
17+
18+
Note:
19+
20+
1 <= S.length <= 20000
21+
S consists only of English lowercase letters.
22+
23+
来源:力扣(LeetCode)
24+
链接:https://leetcode-cn.com/problems/remove-all-adjacent-duplicates-in-string
25+
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
26+
*/
27+
28+
/* O(N) in time and O(N) in time */
29+
#include <string>
30+
#include <stack>
31+
using namespace std;
32+
33+
class Solution {
34+
public:
35+
string removeDuplicates(string S) {
36+
stack<char> s;
37+
string res;
38+
39+
for(int i=0; i<(int)S.size(); ++i){
40+
if( (!s.empty())&&(s.top()==S[i]) ){
41+
s.pop();
42+
}
43+
else{
44+
s.push(S[i]);
45+
}
46+
}
47+
48+
stack<char> l;
49+
while(!s.empty()){
50+
l.push(s.top()); s.pop();
51+
}
52+
while(!l.empty()){
53+
res.push_back(l.top()); l.pop();
54+
}
55+
56+
return res;
57+
}
58+
};

0 commit comments

Comments
 (0)