zoukankan      html  css  js  c++  java
  • 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".
    

    Note:

    1. 1 <= S.length <= 200
    2. 1 <= T.length <= 200
    3. S and T only contain lowercase letters and '#' characters.

    Follow up:

    • Can you solve it in O(N) time and O(1) space?
    //Time: O(n), Space: O(n)
    //有大神用O(1)的方法做出来,详解见如下link
    //https://leetcode.com/problems/backspace-string-compare/discuss/135603/C++JavaPython-O(N)-time-and-O(1)-space
       
     public boolean backspaceCompare(String S, String T) {
            if (S == null || S.length() == 0 || T == null || T.length() == 0) {
                return false;
            }
            
            Stack<Character> s = new Stack<Character>();
            Stack<Character> t = new Stack<Character>();
            
            for (int i = 0; i < S.length(); i++) {
                char c = S.charAt(i);
                
                if (c == '#') {
                    if (!s.isEmpty()) {
                        s.pop();
                    }
                } else {
                    s.push(c);
                }
            }
            
            for (int i = 0; i < T.length(); i++) {
                char c = T.charAt(i);
                
                if (c == '#') {
                    if (!t.isEmpty()) {
                        t.pop();
                    }
                } else {
                    t.push(c);
                }
            }
            
            while (!s.isEmpty() && !t.isEmpty()) {
                if (s.pop() != t.pop()) {
                    return false;
                }
            }
            
            return s.isEmpty() && t.isEmpty();
        }
  • 相关阅读:
    给DOM元素绑定click事件也有学问
    几个JavaScript的浏览器差异处理问题
    CSS样式权重的级联cascade的概念
    你知道HTML标签设计的本意吗?
    一些奇怪的JavaScript试题
    JavaScript如何计算两个日期间的时间差
    Vim默认开启语法标识功能
    理解Python中的继承规则和继承顺序
    An Easy Introduction to CUDA C and C++
    super()
  • 原文地址:https://www.cnblogs.com/jessie2009/p/9777995.html
Copyright © 2011-2022 走看看