题目
给定 S 和 T 两个字符串,其中,#表示退格符,也就是向前删除一个字符。
判断 S 和 T 是否相同。
思路
1,遍历两个字符串,遇到非#,则加入一个队列,遇到#,则从队列尾部删除一个元素。
2,最后比较两个队列的元素是否相同
代码
class Solution {
public boolean backspaceCompare(String S, String T) {
int lenS = S.length();
int lenT = T.length();
S+="a";
T+="a";
// String s = new String("");
LinkedList<Character> s = new LinkedList<Character>();
for (int i=0;i<lenS;i++){
if (S.charAt(i)!='#'){
s.addLast(S.charAt(i));
}else{
if (!s.isEmpty())
s.pollLast();
}
}
// String t = new String("");
LinkedList<Character> t = new LinkedList<Character>();
for (int i=0;i<lenT;i++){
if (T.charAt(i)!='#'){
t.addLast(T.charAt(i));
}else{
if (!t.isEmpty())
t.pollLast();
}
}
return s.equals(t);
}
}