From 03964a1f78a47710b2406d9a4ec00d3d73f0fddd Mon Sep 17 00:00:00 2001 From: Powerstot <77142630+Powerstot@users.noreply.github.com> Date: Wed, 19 May 2021 22:26:03 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E6=94=B91047.=E5=88=A0=E9=99=A4?= =?UTF-8?q?=E5=AD=97=E7=AC=A6=E4=B8=B2=E4=B8=AD=E7=9A=84=E6=89=80=E6=9C=89?= =?UTF-8?q?=E7=9B=B8=E9=82=BB=E9=87=8D=E5=A4=8D=E9=A1=B9=20Java=E7=89=88?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 修改1047.删除字符串中的所有相邻重复项 Java版本 --- ...除字符串中的所有相邻重复项.md | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/problems/1047.删除字符串中的所有相邻重复项.md b/problems/1047.删除字符串中的所有相邻重复项.md index 607a4ccf..32a29c2a 100644 --- a/problems/1047.删除字符串中的所有相邻重复项.md +++ b/problems/1047.删除字符串中的所有相邻重复项.md @@ -122,6 +122,8 @@ public: Java: + +使用 Deque 作为堆栈 ```Java class Solution { public String removeDuplicates(String S) { @@ -144,6 +146,30 @@ class Solution { } } ``` +拿字符串直接作为栈,省去了栈还要转为字符串的操作。 +```Java +class Solution { + public String removeDuplicates(String s) { + // 将 res 当做栈 + StringBuffer res = new StringBuffer(); + // top为 res 的长度 + int top = -1; + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + // 当 top > 0,即栈中有字符时,当前字符如果和栈中字符相等,弹出栈顶字符,同时 top-- + if (top >= 0 && res.charAt(top) == c) { + res.deleteCharAt(top); + top--; + // 否则,将该字符 入栈,同时top++ + } else { + res.append(c); + top++; + } + } + return res.toString(); + } +} +``` Python: ```python3