LeetCode1047(2021.3.9)

LC1047. 删除字符串中的所有相邻重复项

class Solution {
    public String removeDuplicates(String s) {
        StringBuffer stack = new StringBuffer();
        int top = -1;
        for (int i = 0; i < s.length(); ++i) {
            char ch = s.charAt(i);
            if (top >= 0 && stack.charAt(top) == ch) {
                stack.deleteCharAt(top);
                --top;
            }
            else {
                stack.append(ch);
                ++top;
            }
        }
        return stack.toString();
    }
}

留下评论