844. Backspace String Compare - Easy
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?
M1: stack
时间:O(M+N),空间:O(M+N)
class Solution { public boolean backspaceCompare(String S, String T) { Stack<Character> s = new Stack<>(); Stack<Character> t = new Stack<>(); for(int i = 0; i < S.length(); i++) { if(S.charAt(i) != '#') s.push(S.charAt(i)); else if(!s.isEmpty()) s.pop(); } for(int i = 0; i < T.length(); i++) { if(T.charAt(i) != '#') t.push(T.charAt(i)); else if(!t.isEmpty()) t.pop(); } if(s.size() != t.size()) return false; for(int i = 0; i < s.size(); i++) { if(s.pop() != t.pop()) return false; } return true; } }
M2: two pointers
从后往前扫描字符串,用常数cnt统计退格数。遇到‘#’,cnt++;遇到字母并且cnt > 0,cnt--并且指针--;遇到字母但是cnt=0,break退出循环,比较两个字符串对应字符是否相等,不等返回false。如果最后扫描完两个字符串,两个指针都=-1,返回true。如果只扫描完一个字符串,返回false。
时间:O(M+N),空间:O(1)
class Solution { public boolean backspaceCompare(String S, String T) { int p1 = S.length() - 1, p2 = T.length() - 1; int cnt1 = 0, cnt2 = 0; while(p1 >= 0 || p2 >= 0) { while(p1 >= 0) { if(S.charAt(p1) == '#') { p1--;cnt1++; } else if(S.charAt(p1) != '#' && cnt1 > 0) { p1--;cnt1--; } else break; } while(p2 >= 0) { if(T.charAt(p2) == '#') { p2--;cnt2++; } else if(T.charAt(p2) != '#' && cnt2 > 0) { p2--;cnt2--; } else break; } if(p1 == -1 && p2 == -1) return true; if(p1 == -1 || p2 == -1) return false; if(S.charAt(p1) != T.charAt(p2)) return false; p1--;p2--; } return true; } }