题目链接:https://leetcode-cn.com/problems/backspace-string-compare/
题目如下:
思路一:栈
class Solution {
public:
stack<char> intostk(string str){
stack<char> stk;
for(auto e:str){
if(e=='#'&&!stk.empty()) stk.pop();
else if(e!='#'){stk.push(e);cout<<e<<' ';}//注意:"a####c"的情况
}
cout<<endl;
return stk;
}
bool backspaceCompare(string s, string t) {
stack<char> stk1=intostk(s);
stack<char> stk2=intostk(t);
while(!stk1.empty()&&!stk2.empty()){
if(stk1.top()==stk2.top()){
stk1.pop();
stk2.pop();
}else{
return false;
}
}
if(!stk1.empty()||!stk2.empty()) return false;
else return true;
}
};
思路二:双指针
class Solution {
public:
string deal(string str){
if(str=="") return str;
int showindex=0;
for(int fastindex=0;fastindex<str.size();fastindex++){
if(str[fastindex]!='#') str[showindex++]=str[fastindex];
else showindex--;
if(showindex<0) showindex=0;
}
return str.substr(0,showindex);
}
bool backspaceCompare(string s, string t) {
cout<<deal(s)<<endl;
cout<<deal(t)<<endl;
return deal(s)==deal(t);
}
};
解法三:双指针
class Solution {
public:
bool backspaceCompare(string s, string t) {
int j=0;
for(int i=0;i<s.size();i++){
if(s[i]!='#') s[j++]=s[i];
else {
j--;
if(j<0) j=0;
}
}
int k=0;
for(int i=0;i<t.size();i++){
if(t[i]!='#') t[k++]=t[i];
else {
k--;
if(k<0) k=0;
}
}
if(k!=j) return false;
else if(s.substr(0,j)==t.substr(0,k)) return true;
else return false;
}
};