码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode: Backspace String Compare

时间:2019-10-06 11:18:04      阅读:74      评论:0      收藏:0      [点我收藏+]

标签:uil   bec   diff   only   bre   nal   bin   ++   cas   

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

标签:uil   bec   diff   only   bre   nal   bin   ++   cas   

原文地址:https://www.cnblogs.com/EdwardLiu/p/11626564.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!