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
andT
only contain lowercase letters and'#'
characters.
Follow up:
- Can you solve it in
O(N)
time andO(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(); }