Leetcode: Backspace String Compare

Posted neverlandly

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode: 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 and T only contain lowercase letters and ‘#‘ characters.
Follow up:

Can you solve it in O(N) time and O(1) space?

 

 1 class Solution {
 2     public boolean backspaceCompare(String S, String T) {
 3         int i = S.length() - 1, j = T.length() - 1;
 4         int skipS = 0, skipT = 0;
 5 
 6         while (i >= 0 || j >= 0) { // While there may be chars in build(S) or build (T)
 7             while (i >= 0) { // Find position of next possible char in build(S)
 8                 if (S.charAt(i) == ‘#‘) {skipS++; i--;}
 9                 else if (skipS > 0) {skipS--; i--;}
10                 else break;
11             }
12             while (j >= 0) { // Find position of next possible char in build(T)
13                 if (T.charAt(j) == ‘#‘) {skipT++; j--;}
14                 else if (skipT > 0) {skipT--; j--;}
15                 else break;
16             }
17             // If two actual characters are different
18             if (i >= 0 && j >= 0 && S.charAt(i) != T.charAt(j))
19                 return false;
20             // If expecting to compare char vs nothing
21             if ((i >= 0) != (j >= 0))
22                 return false;
23             i--; j--;
24         }
25         return true;
26     }
27 }

 

Complexity Analysis

  • Time Complexity: O(M + N)O(M+N), where M, NM,N are the lengths of S and T respectively.

  • Space Complexity: O(1)O(1).

 

Tricy test cases:

"bxj##tw"
"bxo#j##tw"

and

"ab##"
"c#d#"

and

"bxj##tw"
"bxj###tw"

 

以上是关于Leetcode: Backspace String Compare的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode - Backspace String Compare

Leetcode_easy844. Backspace String Compare

[LeetCode] 844. Backspace String Compare

[LeetCode] Backspace String Compare 回车字符串比较

(栈,双指针) leetcode. 844 Backspace String Compare

LeetCode_844-Backspace String Compare