题目描述(链接:https://ac.nowcoder.com/acm/contest/6912/A 来源:牛客网)
牛牛最近迷上了小游戏,于是他也想对他的01字符串进行一些操作,01字符串上的0和0相邻时会变成1,而1和1相邻时会在字符串上消失,而0和1相邻时什么都不会发生,牛牛现在把初始的字符串给你,你能告诉牛牛这个字符串最后会变成什么样吗。
采用栈实现时,当栈为空时,以为空栈调用top函数会返回NULL,然而调用时会发生段错误。
原来stack 的top函数在栈为空时返回的是超尾-1,所以
The top function returns the topmost element of the stack. You should ensure that there are one or more elements on the stack before calling the top function.
每次调用top()时最好确认一下栈是否为空或者提前压栈一个不可能出现的元素代表栈底
class Solution {
public:
/**
*
* @param str string字符串 初始字符串
* @return string字符串
*/
string solve(string str) {
// write code here
int n = str.length();
if(n <2)
return str;
string res = "";
stack<char> note;
note.push(str[0]);
for(int i = 1; i < n; ++i){
if(!note.empty()){
if(note.top() == '0' && str[i] == '0'){
note.pop();
if(!note.empty() && note.top() == '1'){//如果栈之前还有1直接消失
note.pop();
continue;
}
note.push('1');
continue;
}
else if(note.top() == '1' && str[i] == '1'){
note.pop();
continue;
}
}
note.push(str[i]);
}
while(!note.empty()){
res += note.top();
note.pop();
}
reverse(res.begin(),res.end());
return res;
}
};