【发布时间】:2026-02-11 07:10:01
【问题描述】:
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".
class Solution {
public boolean backspaceCompare(String S, String T) {
Stack<Character> stack1 = new Stack<Character>();
Stack<Character> stack2 = new Stack<Character>();
for(int i=0;i<S.length();i++){
if(S.charAt(i)!='#'){
stack1.push(S.charAt(i));
}else{
stack1.pop();
}
}
for(int j =0;j<T.length();j++){
if(T.charAt(j)!='#'){
stack2.push(S.charAt(j));
}else
stack2.pop();
}
if(stack1==stack2)
return true;
return false;
}
}
我的输出是假的,答案应该是真的为什么这不起作用?
【问题讨论】:
-
你为什么要在
if之前推字符? -
顺便说一句,您应该创建函数来规范化字符串,而不是为每个输入重复代码。
-
另外,
if (cond) return true; else return false;可以简单地为return cond; -
代码很难阅读,也很容易被误解,因为缩进很可怕。请编辑代码并修复它。
-
你的输出是假的,因为
if(stack1==stack2)永远不会是真的。比较使用equals(),而不是==,即return stack1.equals(stack2);
标签: java arrays algorithm stack