思路:消消乐的感觉,就先想到栈;用一个栈存放遍历过的元素,和遍历中的下一个元素相比,相同则出栈,不同则入栈,最终栈内剩余的就是不相同的元素。
class Solution {
public String removeDuplicates(String s) {
//用一个栈存放遍历过的元素
Stack<Character> stack = new Stack();
String ans = "";
for(char c : s.toCharArray()){
//为空时 或 不同元素入栈
if(stack.isEmpty() || stack.peek()!=c){
stack.push(c);
}
else{
//相同元素出栈
stack.pop();
}
}
//整合不相同元素,倒着来
while(!stack.isEmpty()) {
ans = stack.pop() + ans;
}
return ans;
}
}