题解 | #字符串的相邻字符去重#
字符串的相邻字符去重
http://www.nowcoder.com/practice/8c7d55263c624faa8e48a16d92c2e90d
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param s string字符串
* @return string字符串
*/
public String removeDuplicates(String s) {
// write code here
Stack<Character> stack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
if (!stack.isEmpty() && stack.peek() == s.charAt(i)) {
stack.pop();
} else {
stack.push(s.charAt(i));
}
}
StringBuffer sb = new StringBuffer("");
while (!stack.isEmpty()) {
sb.append(stack.pop());
}
sb.reverse();
return new String(sb);
}
}