给定 s 和 t 两个字符串,当它们分别被输入到空白的文本编辑器后,请你判断二者是否相等。# 代表退格字符。
如果相等,返回 true ;否则,返回 false 。
注意:如果对空文本输入退格字符,文本继续为空。
示例 1:
输入:s = "ab#c", t = "ad#c"
输出:true
解释:S 和 T 都会变成 “ac”。
示例 2:
输入:s = "ab##", t = "c#d#"
输出:true
解释:s 和 t 都会变成 “”。
示例 3:
输入:s = "a##c", t = "#a#c"
输出:true
解释:s 和 t 都会变成 “c”。
示例 4:
输入:s = "a#c", t = "b"
输出:false
解释:s 会变成 “c”,但 t 仍然是 “b”。
1.把两个字符串都改为去除"#"及被退掉的字符的新字符串,然后比较新字符串是否相等即可。
class Solution {
public boolean backspaceCompare(String s, String t) {
return build(s).equals(build(t));
}
public String build(String str) {
StringBuilder s = new StringBuilder();
for (int i = 0;i < str.length();i++) {
if (str.charAt(i) != '#') {//遇到的不是#,直接加入
s.append(str.charAt(i));
} else {
if (s.length() > 0) {
s.deleteCharAt(s.length() - 1);//如果遇到了#号,并且还存在字符的情况下,删掉最后一个字符
}
}
}
return s.toString();
}
}
2.从前往后遍历比较的话,因为不知道当前字符的后面存在几个#,因此无法判断当前字符是否是有效字符,因此从后往前进行遍历,统计#出现的次数,跳过对应数量的字符。
class Solution {
public boolean backspaceCompare(String s, String t) {
int index1 = s.length() - 1;
int index2 = t.length() - 1;
int skipS = 0;//s中连续遇到#的次数,即需要连续跳过多少次字符
int skipT = 0;//t中连续遇到#的次数,即需要连续跳过多少次字符
while (index1 >= 0 || index2 >= 0) {
//找到s中第一个需要比较的字符
while (index1 >= 0) {
if (s.charAt(index1) == '#') {//统计需要退的格数
skipS++;
index1--;
} else if (skipS > 0) {//将该退的字符退掉
skipS--;
index1--;
} else {
break;
}
}
//找到t中第一个需要比较的字符
while (index2 >= 0) {
if (t.charAt(index2) == '#') {
skipT++;
index2--;
} else if (skipT > 0) {
skipT--;
index2--;
} else {
break;
}
}
//因为如果第一位是#,可能出现index1、index2为-1,所以要先判断两个有效位是不是都大于等于0,没有越界
if (index1 >= 0 && index2 >= 0) {
if (s.charAt(index1) != t.charAt(index2)) {//当前比较的字符不相等,直接返回false
return false;
}
}
// 其余可能为 false 情况为
// 1. i < 0 && j >= 0
// 2. j < 0 && i >= 0
// 3. i < 0 && j < 0
// 其中,第 3 种情况为符合题意情况,因为这种情况下 s 和 t 都是 index = 0 的位置为 '#' 而这种情况下
// 退格空字符即为空字符,也符合题意,应当返回 True。
// 但是,情况 1 和 2 不符合题意,因为 s 和 t 其中一个是在 index >= 0 处找到了待比较字符,另一个没有找到
// 这种情况显然不符合题意,应当返回 False,下式便处理这种情况。
else if (index1 >=0 || index2 >= 0){
return false;
}
index1--;
index2--;
}
return true;
}
}
题源:力扣