Repeatedly remove all adjacent, repeated characters in a given string from left to right.
No adjacent characters should be identified in the final string.
Examples
"abbbaaccz" → "aaaccz" → "ccz" → "z"
"aabccdc" → "bccdc" → "bdc"
方法1,用stack
public String deDup(String input) {
// Write your solution here
if (input == null){
return null ;
}
if (input.length() == 0){
return input;
}
//use a stack to store the visited value, if repeat then pop
Deque<Character> stack = new LinkedList<>() ;
stack.push(input.charAt(0));
for (int i = 0; i < input.length() ; ) {
if (stack.size() == 0){
stack.push(input.charAt(i));
i++;
continue;
}
if (stack.size() > 0 && stack.peek() != input.charAt(i) ){
stack.push(input.charAt(i));
i++;
} else if (stack.peek() == input.charAt(i)){
// stack contains [a,b] b on top
Character value = stack.peek() ;
//skip all the b
while (i<input.length() && input.charAt(i) == value){
i++ ;
}
stack.pop();
}
}
char[] res = new char[stack.size()] ;
for (int i = stack.size()-1; i >=0 ; i--) {
res[i] = stack.pop() ;
}
return new String(res) ;
}
方法2, 不用stack 通过控制指针来做到
1 public String deDup_noStack(String input) {
2 // Write your solution here
3 if (input == null){
4 return null ;
5 }
6 if (input.length() <= 1){
7 return input;
8 }
9 //use a stack to store the visited value, if repeat then pop
10 char[] chars = input.toCharArray();
11 /*
12 instead of using a extra stack explicitly, we can actually
13 reuse the left side of the original char[] as the "stack"
14 end(including) serves as the stack to be kept
15 * */
16 //
17 int end = 0 ;
18 for (int i = 1; i < chars.length; i++) {
19 //if the stack is empty or no dup.
20 if (end == -1 || chars[end] != chars[i]){
21 chars[++end] = chars[i];
22 } else{
23 //otherwise, we need pop the top element by end--
24 //and ignore all the consecutive duplicate chars.
25 end--;
26 //whenever you use i+1, check out of boundary
27 while (i+1< chars.length && chars[i] == chars[i+1]){
28 i++;//i正好停在最后一个重复的位置上,然后i++ 去下一个非重复的元素
29 }
30 }
31 }
32 //end is index, count is length
33 return new String(chars, 0 , end+1) ;
34 }