Given two strings S
and T
, return if they are equal when both are typed into empty text editors. #
means a backspace character.
Example 1:
Input: S = "ab#c", T = "ad#c" Output: true Explanation: Both S and T become "ac".
Example 2:
Input: S = "ab##", T = "c#d#" Output: true Explanation: Both S and T become "".
Example 3:
Input: S = "a##c", T = "#a#c" Output: true Explanation: Both S and T become "c".
Example 4:
Input: S = "a#c", T = "b" Output: false Explanation: S becomes "c" while T becomes "b".
Note:
1 <= S.length <= 200
1 <= T.length <= 200
S
andT
only contain lowercase letters and'#'
characters.
Follow up:
- Can you solve it in
O(N)
time andO(1)
space?
题目:判断两个输入的字符串是否相等,#代表输入时删除一位
思路:典型的栈的题目,首先我将string转为stack,如果不是#,则入栈;若是#,则栈顶元素出栈。若栈已经为空且为#,则栈仍旧为空。
代码:
class Solution {
public:
bool backspaceCompare(string S, string T) {
stack<char> stackS;
stack<char> stackT;
stackS = StringToAtack(S);
stackT = StringToAtack(T);
while(!stackS.empty()||!stackT.empty()){
if((!stackS.empty()&&stackT.empty())||(stackS.empty()&&!stackT.empty()))//若两个栈一个空一个非空,false
return false;
if(stackS.top()!=stackT.top())//两个栈顶不等false
return false;
stackS.pop();
stackT.pop();
}
return true;
}
stack<char> StringToAtack(string S){//string转换为stack
stack<char> ret;
for(int i=0;i<S.size();i++){
if(S[i]!='#')
ret.push(S[i]);
else{
if(!ret.empty())
ret.pop();
continue;
}
}
return ret;
}
};