给定 s 和 t 两个字符串,当它们分别被输入到空白的文本编辑器后,如果两者相等,返回 true 。# 代表退格字符。
注意:如果对空文本输入退格字符,文本继续为空。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/backspace-string-compare
//给定 s 和 t 两个字符串,当它们分别被输入到空白的文本编辑器后,如果两者相等,返回 true 。# 代表退格字符。
//
// 注意:如果对空文本输入退格字符,文本继续为空。
//
//
//
// 示例 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 = "b"
//输出:false
//解释:s 会变成 "c",但 t 仍然是 "b"。
//
//
//
// 提示:
//
//
// 1 <= s.length, t.length <= 200
// s 和 t 只含有小写字母以及字符 '#'
//
//
//
//
// 进阶:
//
//
// 你可以用 O(n) 的时间复杂度和 O(1) 的空间复杂度解决该问题吗?
//
// Related Topics 栈 双指针 字符串 模拟 👍 431 👎 0
import java.util.Arrays;
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public boolean backspaceCompare(String s, String t) {
char[] sChars = s.toCharArray();
char[] tChars = t.toCharArray();
int sLen = func(sChars);
int tLen = func(tChars);
if (sLen != tLen)
return false;
for (int i = 0; i < sLen; i++)
if (sChars[i] != tChars[i])
return false;
return true;
}
private int func(char [] chars){
int fast = 0;
int slow = 0;
for(;fast< chars.length;fast++){
if(chars[fast] != '#')
chars[slow++] = chars[fast];
else
if(slow>0)
slow--;
}
return slow;
}
}
//leetcode submit region end(Prohibit modification and deletion)
不是#的可以保存,遇见#保存的元素减一,遇见减都要注意数组越界问题,和快搜等while相减一样,注意数组越界问题