首页 > 其他 > 详细

LC-1047 Remove All Adjacent Duplicates In String

时间:2020-07-11 09:07:42      阅读:47      评论:0      收藏:0      [点我收藏+]

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

原文:https://www.cnblogs.com/osoii/p/13282238.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!