给出由小写字母组成的字符串 S
,重复项删除操作会选择两个相邻且相同的字母,并删除它们。
在 S 上反复执行重复项删除操作,直到无法继续删除。
在完成所有重复项删除操作后返回最终的字符串。答案保证唯一。
import java.util.Stack;public class title1047 {public static void main(String[] args) {String s="azxxzy";System.out.println(removeDuplicates(s));}public static String removeDuplicates(String s) {Stack stack=new Stack();for(int i=0;i<s.length();i++){if(stack.isEmpty()){stack.push(s.charAt(i));continue;}//1.取栈顶元素进行比较,栈顶元素不出栈char top=(char)stack.peek();//2.与栈顶元素比较,不相等,入栈if(top!=s.charAt(i)){stack.push(s.charAt(i));}else { //相等,栈顶元素出栈stack.pop();}}//2.将栈内元素转化为字符串String result="";while (!stack.isEmpty()){result=stack.pop()+result;}return result;}
}