diff --git a/problems/0844.比较含退格的字符串.md b/problems/0844.比较含退格的字符串.md index f7823e59..5d29ffb0 100644 --- a/problems/0844.比较含退格的字符串.md +++ b/problems/0844.比较含退格的字符串.md @@ -157,7 +157,7 @@ public: ## 其他语言版本 -### Java: +### Java ```java // 普通方法(使用栈的思路) @@ -214,7 +214,80 @@ public static boolean backspaceCompare(String s, String t) { } ``` +```java +class Solution { + public static boolean backspaceCompare(String s, String t) { + return getStr(s).equals(getStr(t)); + } + public static String getStr(String s) { //使用快慢双指针去除字符串中的# + int slowIndex; + int fastIndex = 0; + StringBuilder builder = new StringBuilder(s); //StringBuilder用于修改字符串 + for(slowIndex = 0; fastIndex < s.length(); fastIndex++) { + if(builder.charAt(fastIndex) != '#') { + builder.setCharAt(slowIndex++,builder.charAt(fastIndex)); + } else { + if(slowIndex > 0) { + slowIndex--; + } + } + } + return builder.toString().substring(0,slowIndex); //截取有效字符串 + } +} +``` + +从后往前双指针: + +```java +class Solution { + public static boolean backspaceCompare(String s, String t) { + int sSkipNum = 0; //记录s的#的个数 + int tSkipNum = 0; //记录t的#的个数 + int sIndex = s.length() - 1; + int tIndex = t.length() - 1; + while(true) { + while(sIndex >= 0) { //每次记录连续的#并跳过被删除的字符 + if(s.charAt(sIndex) == '#') { + sSkipNum++; + } else { + if(sSkipNum > 0) { + sSkipNum--; + } else { + break; + } + } + sIndex--; + } + while(tIndex >= 0) { //每次记录连续的#并跳过被删除的字符 + if(t.charAt(tIndex) == '#') { + tSkipNum++; + } else { + if(tSkipNum > 0) { + tSkipNum--; + } else { + break; + } + } + tIndex--; + } + if(sIndex < 0 || tIndex < 0) { //s 或者 t遍历完了 + break; + } + if(s.charAt(sIndex) != t.charAt(tIndex)) { //当前下标的字符不相等 + return false; + } + sIndex--; + tIndex--; + } + if(sIndex == -1 && tIndex == -1) { //同时遍历完 则相等 + return true; + } + return false; + } +} +``` ### python