比较含退格的字符串
给定 S 和 T 两个字符串,当它们分别被输入到空白的文本编辑器后,判断二者是否相等,并返回结果。 # 代表退格字符。
知识点:栈
思路:用一个函数来得到每个字符串实际上最后得到的字符串。然后对得到的字符串再进行比较。对于一个字符串,当字符不是#时,入栈;当字符是#时,出栈。最后将栈里的字符都pop出来组成字符串我现在好像意识到这样出来的字符串是反过来的,但是是比较两个一不一样,没影响
需要注意的地方:注意出栈的时候,要保证栈不是空的。
if(!stack.empty()){stack.pop();} }
把stack转换为string
char s1[p.size()+1];
i=0;
while(p.empty()==false){
char temp=p.top();
p.pop();
s1[i++]=temp;
}
s1[i]=’\0’;
return s1;
class Solution {
public:
bool backspaceCompare(string S, string T) {
string X=nowstr(S);
string Y=nowstr(T);
if((X.length())!=(Y.length())){ return false;}
else if(X==""&&Y==""){return true;}
else{
for(int i=0;i<X.length();i++){
if(X[i]!=Y[i]){
return false;
}
}
return true;
}
}
string nowstr(string M){
stack<char> stack;
string res="";
int len= M.length();
for(int i=0; i<len;i++){
if(M[i]!='#'){
stack.push(M[i]);
}else{
// char top=stack.top();
if(!stack.empty()){
stack.pop();}
}}
while(!stack.empty()){
res +=stack.top();
stack.pop();
}
return res; }
};