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 "".
Example 3:
Input: s = "a#c", t = "b" Output: false Explanation: s becomes "c" while t becomes "b".
Constraints:
1 <= s.length, t.length <= 200
s
andt
only contain lowercase letters and'#'
characters.
Follow up: Can you solve it in O(n)
time and O(1)
space?
这题一看又是很典型的operation类型的stack题,用stack造出最后的string然后对比就行了。然而提交的时候遇到一个小坑,就是当#出现在第一个的时候,stack.pop()直接报错了,嗯……没有考虑到这种情况。
class Solution {
public boolean backspaceCompare(String s, String t) {
Deque<Character> stack1 = getStack(s);
Deque<Character> stack2 = getStack(t);
while (!stack1.isEmpty() && !stack2.isEmpty()) {
if (stack1.pop() != stack2.pop()) {
return false;
}
}
return stack1.isEmpty() && stack2.isEmpty();
}
private Deque<Character> getStack(String s) {
Deque<Character> stack = new ArrayDeque<>();
for (char c : s.toCharArray()) {
if (c != '#') {
stack.push(c);
} else {
if (!stack.isEmpty()) {
stack.pop();
}
}
}
return stack;
}
}
题目的follow up是用O(1) space完成,于是就不能用stack了。看了答案但是没完全理解透彻,各种判断条件着实令人confusing。
这个方法的主要思想就是从后往前check,这样我们就会先遇到#,然后它的下一个字母char会被删掉,相当于可以预判了。
那么我们就用两个指针分别指向s和t的最后一个字符,从后往前遍历,并且用一个count变量来记录当前有多少个backspace。如果当前遍历到的字符是#,那就count++,如果不是#,那就看看count来判断这个字符要不要被删,如果不需要被删,那我们就找到了这个string里当前的最后一个字符,两个string的最后一个字符做比较,如果不同的话就可以直接return false了。
main idea如上,但是转换成代码就有很多边界条件的判断很tricky了。
首先是最外层的while loop,要同时遍历s和t两个string,比较直观的想法就是i >= 0 || j >= 0,注意这里必须要||而不能是&&的原因是,因为每次循环最后会i--和j--,如果i和j其中只有一个为0,另一个也有可能因为有#而让别的char都删掉的情况,也就是还可能会是相等的(一个例子就是s ="nzp#o#g",t ="b#nzp#o#g",倒数第二个i/j是0, 2)。
里面找last char of a string的while loop,其实比较直观,就i/j >= 0即可。到比较两个string的最后一个字符是否相等时,因为在内层的while loop里我们可能会把i/j减到比0小,所以还得再check一次i/j是否>=0。在最后的返回条件,应该i和j最后都相等,因为如果不相等的话,说明其中有一个一定比另一个剩的字符多(例子:s ="bxj##tw",t ="bxj###tw",最后的i/j是0, -1)。
其实理解的还不是很透彻,需要多巩固,提交了好几次才发现上面的case然后蒙着猜着抄着给AC了的。
class Solution {
public boolean backspaceCompare(String s, String t) {
int i = s.length() - 1;
int j = t.length() - 1;
while (i >= 0 || j >= 0) {
// check the last char in s
int count = 0;
while (i >= 0) {
if (s.charAt(i) == '#') {
count++;
i--;
} else {
// if this char needs to be removed
if (count > 0) {
count--;
i--;
} else {
// until we hit the last char needs to be in the string
break;
}
}
}
// check the last char in t
count = 0;
while (j >= 0) {
if (t.charAt(j) == '#') {
count++;
j--;
} else {
// if this char needs to be removed
if (count > 0) {
count--;
j--;
} else {
// until we hit the last char needs to be in the string
break;
}
}
}
// compare
if (i >= 0 && j >= 0 && s.charAt(i) != t.charAt(j)) {
return false;
}
i--;
j--;
}
return i == j;
}
}
还有一种简洁的解法,但是也用了O(n) space因为构造了新的string:LeetCode - The World's Leading Online Programming Learning Platform