File tree Expand file tree Collapse file tree 1 file changed +21
-4
lines changed Expand file tree Collapse file tree 1 file changed +21
-4
lines changed Original file line number Diff line number Diff line change @@ -250,11 +250,9 @@ func removeDuplicates(s string) string {
250250
251251javaScript:
252252
253+ 法一:使用栈
254+
253255``` js
254- /**
255- * @param {string} s
256- * @return {string}
257- */
258256var removeDuplicates = function (s ) {
259257 const stack = [];
260258 for (const x of s) {
@@ -267,6 +265,25 @@ var removeDuplicates = function(s) {
267265};
268266```
269267
268+ 法二:双指针(模拟栈)
269+
270+ ``` js
271+ // 原地解法(双指针模拟栈)
272+ var removeDuplicates = function (s ) {
273+ s = [... s];
274+ let top = - 1 ; // 指向栈顶元素的下标
275+ for (let i = 0 ; i < s .length ; i++ ) {
276+ if (top === - 1 || s[top] !== s[i]) { // top === -1 即空栈
277+ s[++ top] = s[i]; // 入栈
278+ } else {
279+ top-- ; // 推出栈
280+ }
281+ }
282+ s .length = top + 1 ; // 栈顶元素下标 + 1 为栈的长度
283+ return s .join (' ' );
284+ };
285+ ```
286+
270287TypeScript:
271288
272289``` typescript
You can’t perform that action at this time.
0 commit comments