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();
    }

 

posted @ 2018-10-12 14:32  一丝清风一抹红尘  阅读(330)  评论(0编辑  收藏  举报