874. Backspace String Compare
2026/1/12大约 1 分钟约 323 字
874. Backspace String Compare
难度: Easy
题目描述
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 <= 200sandtonly contain lowercase letters and'#'characters.
Follow up: Can you solve it in O(n) time and O(1) space?
解题思路
代码实现
解决方案
java
class Solution {
public boolean backspaceCompare(String s, String t) {
LinkedList<Character> sStk = new LinkedList<>();
LinkedList<Character> tStk = new LinkedList<>();
char[] sCharArray = s.toCharArray();
char[] tCharArray = t.toCharArray();
for (char c : sCharArray) {
switch (c) {
case '#':
if(!sStk.isEmpty())
sStk.pop();
break;
default:
sStk.push(c);
}
}
for (char c : tCharArray) {
switch (c) {
case '#':
if(!tStk.isEmpty())
tStk.pop();
break;
default:
tStk.push(c);
}
}
return Arrays.equals(sStk.toArray(), tStk.toArray());
}
}