• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

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"

 

posted @ 2019-10-06 09:58  neverlandly  阅读(131)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3