From 5e0b3fe0d9534865be8228faec32e83501bcc773 Mon Sep 17 00:00:00 2001 From: xiongxi Date: Mon, 21 Apr 2025 22:12:35 +0800 Subject: [PATCH] =?UTF-8?q?=E8=A1=A5=E5=85=851047=E7=94=A8=E6=95=B0?= =?UTF-8?q?=E7=BB=84=E6=A8=A1=E6=8B=9F=E6=A0=88=E7=9A=84go=E5=AE=9E?= =?UTF-8?q?=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...73\351\207\215\345\244\215\351\241\271.md" | 33 ++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git "a/problems/1047.\345\210\240\351\231\244\345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\346\211\200\346\234\211\347\233\270\351\202\273\351\207\215\345\244\215\351\241\271.md" "b/problems/1047.\345\210\240\351\231\244\345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\346\211\200\346\234\211\347\233\270\351\202\273\351\207\215\345\244\215\351\241\271.md" index 01d33fbff7..f37ec6355c 100644 --- "a/problems/1047.\345\210\240\351\231\244\345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\346\211\200\346\234\211\347\233\270\351\202\273\351\207\215\345\244\215\351\241\271.md" +++ "b/problems/1047.\345\210\240\351\231\244\345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\346\211\200\346\234\211\347\233\270\351\202\273\351\207\215\345\244\215\351\241\271.md" @@ -265,7 +265,39 @@ func removeDuplicates(s string) string { return string(res) } ``` +用数组模拟栈: + +~~~go +func removeDuplicates(s string) string { + arr := make([]byte, len(s)) + bottom := 0 + for i := 0; i < len(s); { + // bottom为0时单独考虑 + if bottom == 0 { + arr[bottom] = s[i] + i++ + bottom++ + continue + } + // bottom指向下一个arr赋值的位置 + if s[i] == arr[bottom-1] { + i++ + bottom-- + } else { + arr[bottom] = s[i] + i++ + bottom++ + } + } + // 利用切片 + return string(arr[:bottom]) +} +~~~ + + + 拿字符串直接作为栈,省去了栈还要转为字符串的操作 + ```go func removeDuplicates(s string) string { var stack []byte @@ -520,4 +552,3 @@ def remove_duplicates(s) end ``` -