From 642734522dcb0aa693ab651a6591fd315a721db2 Mon Sep 17 00:00:00 2001 From: ekertree Date: Thu, 18 Aug 2022 20:07:34 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200844=E6=AF=94=E8=BE=83?= =?UTF-8?q?=E5=90=AB=E9=80=80=E6=A0=BC=E7=9A=84=E5=AD=97=E7=AC=A6=E4=B8=B2?= =?UTF-8?q?=20Java=20=E7=89=88=E6=9C=AC=20=E5=88=A0=E9=99=A4=20Java?= =?UTF-8?q?=E6=A0=87=E9=A2=98=E7=9A=84=E5=86=92=E5=8F=B7=20=E7=BB=9F?= =?UTF-8?q?=E4=B8=80=E9=A1=B5=E9=9D=A2=E6=A0=BC=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0844.比较含退格的字符串.md | 75 +++++++++++++++++++- 1 file changed, 74 insertions(+), 1 deletion(-) 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