给定一个字符串 s 和一个整数 k,ak 重复删除包括从 s 中选择 k 个相邻且相等的字母并将它们删除,使删除的子字符串的左侧和右侧连接在一起。
我们反复对 s 进行 k 次重复删除,直到我们不再可以为止。
在完成所有此类重复删除后返回最终字符串。保证答案是唯一的。
按照我写的代码。
class Solution {
public:
string removeDuplicates(string s, int k) {
stack<pair<char,int>> st;
string str;
int idx = 0;
st.push({s[idx++],1});
while(idx < s.size()){
if(st.empty()) {
st.push({s[idx++],1});
continue;
}
pair<char,int> p = st.top();
if(p.first == s[idx]){
if(p.second < k-1){
p.second++; // problem point
idx++;
}
else {
st.pop();
idx++;
}
}
else{
st.push({s[idx++],1});
}
}
while(!st.empty()){
pair<char,int> p = st.top();
st.pop();
str.push_back(p.first);
}
reverse(str.begin(),str.end());
return str;
}
};
例如,输入字符串是 aabbbc,int 是 3。正确的输出是 aac,但我的输出是 abc。所以我调试了那个代码。我认为问题是“pair<char,int> p = st.top();”。初始化 p 有问题吗?但我不明白出了什么问题。当 aabbbc 的第四个索引为 b 时,p.second 为 2。但在下一个循环中 p.second 不记得了。p.second 是 1. 有什么问题?