Given two strings s and t, return true 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 “”.
Constraints:
1 <= s.length, 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?
两个字符串s和t,它们可能含有退格符“#”,遇到一个退格“#”就是把前面一个字符消掉,
判断s和t是否相等。
思路:
方法一:
本题最容易想到的是stack.
遇到字母进栈,遇到’#'则出栈。
下面用char array模仿stack, stop代表 s 的栈顶,ttop代表 t 的栈顶。
最后比较栈的长度和栈内元素即可。
public boolean backspaceCompare(String s, String t) {
char[] chs = s.toCharArray();
char[] cht = t.toCharArray();
if(chs.length == 0 && cht.length == 0) return true;
int stop = -1;
int ttop = -1;
for(int i = 0; i < chs.length; i++) {
if(chs[i] == '#') {
if(stop >= 0) stop --;
} else {
stop ++;
chs[stop] = chs[i];
}
}
for(int i = 0; i < cht.length; i++) {
if(cht[i] == '#') {
if(ttop >= 0) ttop --;
} else {
ttop ++;
cht[ttop] = cht[i];
}
}
if(stop != ttop) return false;
for(int i = 0; i <= stop; i++) {
if(chs[i] != cht[i]) return false;
}
return true;
}
但是题目中follow up 指出是否能用时间负责度O(n), 空间复杂度O(1).
上面的方法空间复杂度是O(n).
O(1)的话只能考虑用指针了。
方法二:
现用指针,从字符串的末尾开始,倒着走,
遇到“#”,则删掉前面的字符。那有可能有连续多个的“#”,这时需要一个计数器,记录需要删掉前面多少个字符。
还有可能遇到一种情况就是字符串长度不一致,可能一个指针已经超出左边界了,但是另一个还没到左边界。
方法一的速度更快。
public boolean backspaceCompare(String s, String t) {
int sp = s.length() - 1;
int tp = t.length() - 1;
int sNext = 0;
int tNext = 0;
while(sp >= 0 || tp >= 0) {
while(sp >= 0) {
if(s.charAt(sp) == '#') {
sNext ++;
sp --;
} else if(sNext > 0) {
sNext --;
sp --;
} else {
break;
}
}
while(tp >= 0) {
if(t.charAt(tp) == '#') {
tNext ++;
tp --;
} else if(tNext > 0) {
tNext --;
tp --;
} else {
break;
}
}
if(sp >= 0 && tp >= 0) {
if(s.charAt(sp) != t.charAt(tp)) return false;
}
if((sp >= 0) != (tp >= 0)) return false;
sp --;
tp --;
}
return true;
}