英文版 LeetCode 每日一题(2020 年 4 月 10 日)
地址:https://leetcode-cn.com/problems/backspace-string-compare/
地址:https://leetcode.com/explore/featured/card/30-day-leetcoding-challenge/529/week-2/3291/
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 <= 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?
思路一:使用栈
Java 代码:
import java.util.ArrayDeque;
import java.util.Deque;
public class Solution3 {
public boolean backspaceCompare(String S, String T) {
return simplify(S).equals(simplify(T));
}
private String simplify(String str){
Deque<Character> stack = new ArrayDeque<>();
char[] charArray = str.toCharArray();
for (char c : charArray) {
if (c != '#') {
stack.addLast(c);
} else if (!stack.isEmpty()) {
stack.pollLast();
}
}
return stack.toString();
}
public static void main(String[] args) {
String S = "ab#c";
String T = "ad#c";
// String S = "ab##";
// String T = "c#d#";
// String S = "a##c";
// String T = "#a#c";
// String S = "a#c";
// String T = "b";
Solution3 solution3 = new Solution3();
boolean res = solution3.backspaceCompare(S, T);
System.out.println(res);
}
}
思路二:双指针
参考:https://www.cnblogs.com/grandyang/p/10447783.html
我想到了双指针,但是没有想到从后向前遍历,还有具体的细节懒得想了,优化了原作者的代码。
Java 代码:
public class Solution {
public boolean backspaceCompare(String S, String T) {
char[] charArray1 = S.toCharArray();
char[] charArray2 = T.toCharArray();
int len1 = S.length();
int len2 = T.length();
// 连续出现 # 的个数
int cnt1 = 0;
int cnt2 = 0;
int i = len1 - 1;
int j = len2 - 1;
while (i >= 0 || j >= 0) {
// 逻辑上应该先处理 # 号
while (i >= 0 && (charArray1[i] == '#' || cnt1 > 0)) {
if (charArray1[i] == '#') {
cnt1++;
} else {
cnt1--;
}
i--;
}
while (j >= 0 && (charArray2[j] == '#' || cnt2 > 0)) {
if (charArray2[j] == '#') {
cnt2++;
} else {
cnt2--;
}
j--;
}
// 这里处理数组下标越界的情况
if (i < 0 || j < 0) {
return i == j;
}
// 这是最简单的情况
if (charArray1[i] != charArray2[j]) {
return false;
}
// 然后继续向前遍历
j--;
i--;
}
// 细节特别多,到这里就完了
return i == j;
}
}