# LeetCode.1047-重复删除字符串中的所有相邻重复项

### 01 看题和准备

• 1 <= S.length <= 20000

• S仅由英文小写字母组成。

### 02 第一种解法

public String removeDuplicates(String S) {
boolean flag = true;
while (flag) {
flag = false;
int n = S.length()-1;
for (int i=0; i<n; i++) {
if (S.charAt(i) == S.charAt(i+1)) {
S = S.substring(0, i)+
S.substring(i+2, S.length());
flag = true;
break;
}
}
}
return S;
}

### 03 第二种解法

public String removeDuplicates2(String S) {
Stack<Character> stack = new Stack<Character>();
int n = S.length();
for (int i=0; i<n; i++) {
if (!stack.isEmpty() && S.charAt(i) == stack.peek()) {
stack.pop();
} else {
stack.push(S.charAt(i));
}
}
StringBuilder sb = new StringBuilder();
while (!stack.isEmpty()) {
sb.append(stack.pop());
}
return sb.reverse().toString();
}

### 04 第三种解法

public String removeDuplicates3(String S) {
StringBuilder sb = new StringBuilder();
int n = S.length();
for (int i=0; i<n; i++) {
int size = sb.length();
if (size > 0 && sb.charAt(size-1) == S.charAt(i)) {
sb.deleteCharAt(size-1);
} else {
sb.append(S.charAt(i));
}
}
return sb.toString();
}

### 05 第四种解法

public String removeDuplicates4(String S) {
int n = S.length(), index = 0;
char[] arr = new char[n];
for (int i=0; i<n; i++) {
if (index > 0 && arr[index-1] == S.charAt(i)) {
index--;
} else {
arr[index++] = S.charAt(i);
}
}
return new String(arr, 0, index);
}

### 06 小结

posted @ 2019-07-22 08:47  程序员小川  阅读(...)  评论(...编辑  收藏