class Solution {
public:
/*
当栈为空时:
1. 字符串不为空,进栈;
2. 字符串为空,返回
当栈不为空时:
比较栈顶和字符
a)相等,则出栈
b)不等,则入栈
当字符串遍历完成,将栈里的字符都插入到res的 0 位置,耗时了。
先添加到尾部,再翻转。
*/
string removeDuplicates(string s) {
stack<char> st1;
string res;
for (int i = 0; i < s.length(); i++) {
if (st1.empty()) {
st1.push(s[i]);
}
else {
if (st1.top() == s[i]) {
st1.pop();
}
else {
st1.push(s[i]);
}
}
}
while (!st1.empty()) {
char x = st1.top();
//Char 17: error: no matching member function for call to 'insert'
// res.insert(0, x);
// 每次在字符串的首部添加字符。。导致程序消耗增加。
// res = x + res;
// 先添加完,后翻转
res += x;
st1.pop();
}
// 用algorithm函数
//reverse(res.begin(), res.end());
// 1 2 3 4 5
// 原地翻转
int len = res.length();
for (int i = 0; i < len/2; i++) {
swap(res[i], res[len - i - 1]);
}
return res;
}
};
总结
- 想问题的时候,没注意内存消耗问题
- strrev函数只对字符数组有效,对string类型是无效的。
- reverse函数是反转容器中的内容,对字符数组无效。