GuilinDev

Lc1047

05 August 2008

1047 Remove All Adjacent Duplicates In String

删除字符串中所有的相邻并且重复的字符(反复执行直到最后无法删除) - 栈

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
    public String removeDuplicates(String s) {
        char[] cs = s.toCharArray();
        Deque<Character> d = new ArrayDeque<>();
        for (char c : cs) {
            if (!d.isEmpty() && d.peekLast().equals(c)) {
                d.pollLast();
            } else {
                d.addLast(c);
            }
        }
        StringBuilder sb = new StringBuilder();
        while (!d.isEmpty()) sb.append(d.pollLast());
        sb.reverse();
        return sb.toString();
    }
}