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 ``` -