解题思路:
方法一:栈
class Solution {public String removeDuplicates(String s) {Deque<Character> stack = new ArrayDeque<>();for (char c : s.toCharArray()) {if (stack.isEmpty() || stack.peek() != c) stack.push(c);else stack.pop();}String str = "";while (!stack.isEmpty()) str = stack.pop() + str;return str;}
}
方法二:字符串(拿字符串直接作为栈,省去了栈还要转为字符串的操作)
可能没有栈那么好直观理解
class Solution {public String removeDuplicates(String s) {StringBuffer str = new StringBuffer();int top = -1;for (int i = 0; i < s.length(); i++) {char c = s.charAt(i);if (top >= 0 && c == str.charAt(top)) {str.deleteCharAt(top);top--;} else {str.append(c);top++;}}return str.toString();}
}