删除字符串中的所有相邻重复项 (Remove All Adjacent Duplicates In String)

 

思路:

// @Title: 删除字符串中的所有相邻重复项 (Remove All Adjacent Duplicates In String)
// @Author: qisiii
// @Date: 2024-09-14 12:06:14
// @Runtime: 70 ms
// @Memory: 44.2 MB
// @comment: 
// @flag: 
class Solution {
    public String removeDuplicates(String s) {
        Stack<Character> stack=new Stack<>();
        char[] arr=s.toCharArray();
        for(char c:arr){
            if(stack.isEmpty()){
                stack.push(c);
            }else if(stack.peek()==c){
                stack.pop();
            }else{
                 stack.push(c);
            }
        }
        char[] result=new char[stack.size()];
        for(int i=result.length-1;i>=0;i--){
            result[i]=stack.pop();
        }
        return new String(result);
    }
}
Licensed under CC BY-NC-SA 4.0
最后更新于 2024-10-18