topic
train of thought
In fact, the idea is not too difficult, what I want to record is that I am too careless. Originally, I wanted to write the judgment of the if statement together, and the result. . .
At first I wrote if(!sta.empty()&&str[i]=='#'),
but there is a problem, if the stack sta is empty (!sta.empty() is false), then if the current str [i] is '#', because of the "short circuit", the if statement is directly false, and the else statement is executed, and '#' is pushed onto the stack. .
the code
error code
class Solution {
public:
stack<char> moveToStack(string& str){
stack<char> sta;
int size = str.size();
for(int i=0;i<size;i++){
if(!sta.empty()&&str[i]=='#') sta.pop();
else sta.push(str[i]);
}
return sta;
}
bool backspaceCompare(string s, string t) {
stack<char> sta1 = moveToStack(s);
stack<char> sta2 = moveToStack(t);
while(!sta1.empty()&&!sta2.empty()){
char tmp1 = sta1.top(); sta1.pop();
char tmp2 = sta2.top(); sta2.pop();
if(tmp1!=tmp2) return false;
}
return sta1.empty()&&sta2.empty();
}
};
AC code
class Solution {
public:
stack<char> moveToStack(string& str){
stack<char> sta;
int size = str.size();
for(int i=0;i<size;i++){
if(str[i]=='#'){
if(!sta.empty()) sta.pop();
}
else sta.push(str[i]);
}
return sta;
}
bool backspaceCompare(string s, string t) {
stack<char> sta1 = moveToStack(s);
stack<char> sta2 = moveToStack(t);
while(!sta1.empty()&&!sta2.empty()){
char tmp1 = sta1.top(); sta1.pop();
char tmp2 = sta2.top(); sta2.pop();
if(tmp1!=tmp2) return false;
}
return sta1.empty()&&sta2.empty();
}
};