package com.zmz.algorithm.stackQueue;
import java.util.Stack;
/**
* @author 张明泽
* Create by 2022/5/31 21:30
* 删除字符串中的所有相邻重复项
* LeetCode-1047
*/
public class DeleteRepeatString {
public static void main(String[] args) {
String str = "abbaca";
String result = removeDuplicates(str);
System.out.println(result);
}
public static String removeDuplicates(String str) {
Stack<Character> stack = new Stack<>();
for (char c : str.toCharArray()) {
if (!stack.isEmpty() && c == stack.peek()) {
stack.pop();
} else {
stack.push(c);
}
}
StringBuffer stringBuffer = new StringBuffer();
while (!stack.isEmpty()) {
stringBuffer.append(stack.pop());
}
return stringBuffer.reverse().toString();
}
}
最后修改:2022 年 06 月 02 日 10 : 22 AM
© 允许规范转载