Given two strings
S
andT
, 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?
很直接的想到用栈来解决(如下),但是题目要求空间复杂度为O(1),所以只能使用其他方法。注意到#只对前面一个字符产生影响,所以从后往前看就是遇到#就把角标移动一个。
class Solution {
public boolean backspaceCompare(String S, String T) {
Stack<Character> stack1 = new Stack<>();
Stack<Character> stack2 = new Stack<>();
char c;
for(int i=0;i<S.length();i++){
c = S.charAt(i);
if(c!='#'){
stack1.push(c);
}else{
if(!stack1.isEmpty()){
stack1.pop();
}
}
}
for(int i=0;i<T.length();i++){
c = T.charAt(i);
if(c!='#'){
stack2.push(c);
}else{
if(!stack2.isEmpty()){
stack2.pop();
}
}
}
while(!stack1.isEmpty()&&!stack2.isEmpty()){
if(stack1.pop()!=stack2.pop())
return false;
}
return stack1.isEmpty()&&stack2.isEmpty();
}
}
class Solution {
public boolean backspaceCompare(String S, String T) {
int i = S.length()-1;
int j = T.length()-1;
int skipi = 0; //记录#数量
int skipj = 0; //记录#数量
while(i>=0||j>=0){
while(i>=0){
if(S.charAt(i)=='#'){
skipi++;
i--; //碰到#号,往前移动一个
}else if(skipi>0){ //上面只移动一个而不是直接移动两个的原因就是有可能两个#相连
i--;
skipi--;
}else{
break;
}
}
while(j>=0){
if(T.charAt(j)=='#'){
skipj++;
j--;
}else if(skipj>0){
j--;
skipj--;
}else{
break;
}
}
if(i>=0&&j>=0&&S.charAt(i)!=T.charAt(j))
return false;
if((i>=0)!=(j>=0))
return false;
i--;
j--;
}
return true;
}
}