zoukankan      html  css  js  c++  java
  • LeetCode 1047. 删除字符串中的所有相邻重复项(Remove All Adjacent Duplicates In String)

    1047. 删除字符串中的所有相邻重复项
    1047. Remove All Adjacent Duplicates In String

    题目描述

    LeetCode1047. Remove All Adjacent Duplicates In String简单

    Java 实现

    import java.util.Stack;
    
    class Solution {
        public String removeDuplicates(String S) {
            if (S == null || S.length() == 0) {
                return S;
            }
            Stack<Character> stack = new Stack<>();
            char[] c = S.toCharArray();
            for (int i = 0; i < c.length; i++) {
                if (!stack.isEmpty() && c[i] == stack.peek()) {
                    stack.pop();
                } else {
                    stack.push(c[i]);
                }
            }
            StringBuffer sb = new StringBuffer();
            while (!stack.isEmpty()) {
                sb.insert(0, stack.pop());
            }
            return sb.toString();
        }
    }
    
    class Solution {
        public String removeDuplicates(String S) {
            int n = S.length();
            int i = 0;
            char[] c = new char[n];
            for (int j = 0; j < n; j++) {
                if (i > 0 && c[i - 1] == S.charAt(j)) {
                    i--;
                } else {
                    c[i++] = S.charAt(j);
                }
            }
            return new String(c, 0, i);
        }
    }
    

    参考资料

  • 相关阅读:
    js5
    js4
    js(3)
    JS内容(2)
    html复习
    js介绍及内容(1)
    定位2
    position定位
    CSS
    列表及行块转变
  • 原文地址:https://www.cnblogs.com/hgnulb/p/10988443.html
Copyright © 2011-2022 走看看