zoukankan      html  css  js  c++  java
  • 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"
  • 相关阅读:
    设计模式
    刷新所有视图存储过程
    js杨辉三角控制台输出
    2018申请淘宝客AppKey
    w3c标准 dom对象 事件冒泡和事件捕获
    promise原理
    vue virtual Dom
    css学习
    seo优化
    新概念学习
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/11626564.html
Copyright © 2011-2022 走看看