LeetCode 844. Backspace String Compare
原题链接在这里: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:
class Solution { public boolean backspaceCompare(String S, String T) { if(S == null || T == null){ return S == T; } int m = S.length(); int n = T.length(); int i = m - 1; int j = n - 1; int cntS = 0; int cntT = 0; while(i >= 0 || j >= 0){ while(i >= 0 && (S.charAt(i) == ‘#‘ || cntS > 0)){ if(S.charAt(i) == ‘#‘){ cntS++; }else{ cntS--; } i--; } while(j >= 0 && (T.charAt(j) == ‘#‘ || cntT > 0)){ if(T.charAt(j) == ‘#‘){ cntT++; }else{ cntT--; } j--; } if(i >= 0 && j >= 0 && S.charAt(i) == T.charAt(j)){ i--; j--; }else{ return i == -1 && j == -1; } } return true; } }
相关推荐
Lzs 2020-10-23
聚合室 2020-11-16
零 2020-09-18
Justhavefun 2020-10-22
jacktangj 2020-10-14
ChaITSimpleLove 2020-10-06
Andrea0 2020-09-18
周游列国之仕子 2020-09-15
afanti 2020-09-16
88234852 2020-09-15
YClimb 2020-09-15
风雨断肠人 2020-09-04
卖口粥湛蓝的天空 2020-09-15
stulen 2020-09-15
pythonxuexi 2020-09-06
abfdada 2020-08-26
梦的天空 2020-08-25