844. 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".

 [暴力解法]:

时间分析:

空间分析:

 [优化后]:

时间分析:

空间分析:

[奇葩输出条件]:

[奇葩corner case]:

[思维问题]:以为要用stack:可是应该考虑这个占的空间比较大

[英文数据结构或算法,为什么不用别的数据结构或算法]:

统计numOfBlankspaces的个数,然后看i j是否同时倒数到1

[一句话思路]:

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

[一刷]:

[二刷]:

[三刷]:

[四刷]:

[五刷]:

  [五分钟肉眼debug的结果]:

[总结]:

统计numOfBlankspaces的个数,然后看i j是否同时倒数到1

[复杂度]:Time complexity: O(n) Space complexity: O(n)

[算法思想:迭代/递归/分治/贪心]:

[关键模板化代码]:

[其他解法]:

[Follow Up]:

[LC给出的题目变变变]:

 [代码风格] :

 [是否头一次写此类driver funcion的代码] :

 [潜台词] :

 

class Solution {
    public boolean backspaceCompare(String S, String T) {
        for (int i = S.length() - 1, j = T.length() - 1; ; i--, j--) {
            for (int numOfBlankspaces = 0; i >= 0 && (numOfBlankspaces > 0 || S.charAt(i) == '#'); i--) {
                numOfBlankspaces = S.charAt(i) == '#' ? numOfBlankspaces + 1 : numOfBlankspaces - 1; 
            }
            for (int numOfBlankspaces = 0; j >= 0 && (numOfBlankspaces > 0 || T.charAt(j) == '#'); j--) {
                numOfBlankspaces = T.charAt(j) == '#' ? numOfBlankspaces + 1 : numOfBlankspaces - 1; 
            }
            if (i == -1 || j == -1 || S.charAt(i) != T.charAt(j)) return (i == -1) && (j == -1);
        }
    }
}
View Code

 

posted @ 2018-08-13 21:02  苗妙苗  阅读(292)  评论(0)    收藏  举报