LC-1047 Remove All Adjacent Duplicates In String

Posted osoii

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LC-1047 Remove All Adjacent Duplicates In String相关的知识,希望对你有一定的参考价值。

https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string/

给一个字符串,如果出现两个相邻的相同字符,就将它们一同删去,重复这个操作直到不能继续做为止,返回最后的字符串

 

一开始我是用类似递归的方式重复对这个字符串进行操作,结果时间和内存都高的吓人

后来看题解提到了使用栈,这才恍然大悟

这是个比较简单的小题,记录在这里是为了提醒自己对栈的应用

遍历字符串,对每个字符,观察当前栈顶元素是否与它一样。如果不是,就入栈;如果是,就不入栈,并且栈pop。

技术图片
 1 class Solution {
 2 public:
 3     string removeDuplicates(string S) {
 4         stack<char> st;
 5         for (int i = 0; i < S.length(); i++) {
 6             if (st.empty() || S[i] != st.top()) {
 7                 st.push(S[i]);
 8             }
 9             else {
10                 st.pop();
11             }
12         }
13         string ret = "";
14         while (!st.empty()) {
15             ret.push_back(st.top());
16             st.pop();
17         }
18         for (int i = 0; i < ret.length() / 2; i++) {
19             char tmp = ret[i];
20             ret[i] = ret[ret.length() - 1 - i];
21             ret[ret.length() - 1 - i] = tmp;
22         }
23         return ret;
24     }
25 };
代码

 

以上是关于LC-1047 Remove All Adjacent Duplicates In String的主要内容,如果未能解决你的问题,请参考以下文章