原题链接在这里:https://leetcode.com/problems/backspace-string-compare/
题目:
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?
题解:
Could easily do it with stack. The follow up is to use O(N) time and O(1) space.
We could iterate the string back to front. Accumlate he # and use it when it is no #.
Then check if two chars are the same, if yes, move both pointers.
If not, check if two pointers alreay come to -1.
Time Complexity: O(m+n). m = S.length(). n = T.length().
Space: O(1).
AC Java:
1 class Solution { 2 public boolean backspaceCompare(String S, String T) { 3 if(S == null || T == null){ 4 return S == T; 5 } 6 7 int m = S.length(); 8 int n = T.length(); 9 int i = m - 1; 10 int j = n - 1; 11 int cntS = 0; 12 int cntT = 0; 13 14 while(i >= 0 || j >= 0){ 15 while(i >= 0 && (S.charAt(i) == '#' || cntS > 0)){ 16 if(S.charAt(i) == '#'){ 17 cntS++; 18 }else{ 19 cntS--; 20 } 21 22 i--; 23 } 24 25 while(j >= 0 && (T.charAt(j) == '#' || cntT > 0)){ 26 if(T.charAt(j) == '#'){ 27 cntT++; 28 }else{ 29 cntT--; 30 } 31 32 j--; 33 } 34 35 if(i >= 0 && j >= 0 && S.charAt(i) == T.charAt(j)){ 36 i--; 37 j--; 38 }else{ 39 return i == -1 && j == -1; 40 } 41 } 42 43 return true; 44 } 45 }