1047. 删除字符串中的所有相邻重复项
- 此题是将字符串的每个元素依次加入栈中,如果此时栈顶的元素与要加入的相同,就把二者都弹出
- 否则就正常加入
- 最后生成结果字符串的时候将栈中的元素弹出并且倒序插入即可
class Solution {
public:
string removeDuplicates(string S) {
stack<char> st;
for (char s : S) {
if (st.empty() || s != st.top()) {
st.push(s);
} else {
st.pop(); // s 与 st.top()相等的情况
}
}
string result = "";
while (!st.empty()) { // 将栈中元素放到result字符串汇总
result += st.top();
st.pop();
}
reverse (result.begin(), result.end()); // 此时字符串需要反转一下
return result;
}
};