844. Backspace String Compare
代码如下
class Solution {
public:
bool backspaceCompare(string s, string t) {
int first=s.length()-1,second=t.length()-1;
int space_s=0,space_t=0;
while(first>=0 || second>=0){
while(first>=0){
if(s[first]=='#'){
first--;
space_s++;
}else if(space_s){
first--;
space_s--;
}else if(!space_s){
break;
}
}
while(second>=0){
if(t[second]=='#'){
second--;
space_t++;
}else if(space_t){
space_t--;
second--;
}else if(!space_t){
break;
}
}
if(first>=0 && second>=0){
if(s[first]!=t[second])
return false;
}else{
if(first>=0|| second>=0)
return false;
}
first--,second--;
}
return true;
}
};
大致的想法,大循环用于比较小循环找到的字符是否相等,同时,考虑到两个字符串不一定相等,所以是大循环是或的条件,但在比较字符时if是且的条件,这里不要在外面判断,要在大循环里就把长度不同的给排掉,因为出了循环不好判断,还有个原因左边化完全变空字符串,此时也是满足条件