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.
Note that after backspacing an empty text, the text will continue empty.
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?
Solution1:
class Solution {
public boolean backspaceCompare(String S, String T) {
StringBuilder sb = new StringBuilder();
for (char c : S.toCharArray()) {
if (c == '#') {
sb.setLength(Math.max(0, sb.length() - 1));
} else {
sb.append(c);
}
}
String s = sb.toString();
sb = new StringBuilder();
for (char c : T.toCharArray()) {
if (c == '#') {
sb.setLength(Math.max(0, sb.length() - 1));
} else {
sb.append(c);
}
}
return s.equals(sb.toString());
}
}
Solution2:
scan from end to front. When count"#" != 0 or charAt(i) == '#', increase/decrease number of '#' till we don't have '#'.
class Solution {
public boolean backspaceCompare(String S, String T) {
int count1 = 0, count2 = 0;
for (int p1 = S.length() - 1, p2 = T.length() - 1; p1 >= 0 || p2 >= 0; p1 --, p2 --) {
while (p1 >= 0 && (count1 > 0 || S.charAt(p1) == '#')) {
if (S.charAt(p1) == '#') {
count1 ++;
} else {
count1 --;
}
p1 --;
}
while (p2 >= 0 && (count2 > 0 || T.charAt(p2) == '#')) {
if (T.charAt(p2) == '#') {
count2 ++;
} else {
count2 --;
}
p2 --;
}
if (p1 < 0 && p2 < 0) {
return true;
}
if (p1 < 0 || p2 < 0) {
return false;
}
if (S.charAt(p1) != T.charAt(p2)) {
return false;
}
}
return true;
}
}