1047. 删除字符串中的所有相邻重复项
1047. Remove All Adjacent Duplicates In String
题目描述
LeetCode1047. Remove All Adjacent Duplicates In String简单
Java 实现
import java.util.Stack;
class Solution {
public String removeDuplicates(String S) {
if (S == null || S.length() == 0) {
return S;
}
Stack<Character> stack = new Stack<>();
char[] c = S.toCharArray();
for (int i = 0; i < c.length; i++) {
if (!stack.isEmpty() && c[i] == stack.peek()) {
stack.pop();
} else {
stack.push(c[i]);
}
}
StringBuffer sb = new StringBuffer();
while (!stack.isEmpty()) {
sb.insert(0, stack.pop());
}
return sb.toString();
}
}
class Solution {
public String removeDuplicates(String S) {
int n = S.length();
int i = 0;
char[] c = new char[n];
for (int j = 0; j < n; j++) {
if (i > 0 && c[i - 1] == S.charAt(j)) {
i--;
} else {
c[i++] = S.charAt(j);
}
}
return new String(c, 0, i);
}
}
参考资料