首页 > 其他分享 >【栈】LeetCode 1209. 删除字符串中的所有相邻重复项 II

【栈】LeetCode 1209. 删除字符串中的所有相邻重复项 II

时间:2023-01-05 10:48:17浏览次数:58  
标签:1209 栈顶 整数 stack II sb new LeetCode

题目链接

1209. 删除字符串中的所有相邻重复项 II

思路

用栈存储 Pair<Character, Integer> ,整数表示该字符连续出现的次数。遍历字符串 s 将其中的字符 c 依次压入栈顶并判断:

  1. c 和栈顶元素相同,则其整数部分=栈顶整数部分+1,此时如果 c 的整数部分为 k 则进行弹出操作。
  2. c和栈顶元素不同,则 c 的整数部分为1,压入栈顶。

代码

class Solution{
    public String removeDuplicates(String s, int k){

        Stack<Pair<Character, Integer>> stack = new Stack<>();
        
        for(char c : s.toCharArray()){
            if(!stack.isEmpty() && stack.peek().getKey() == c){
                stack.push(new Pair<>(c, stack.peek().getValue() + 1));
            }else{
                stack.push(new Pair<>(c, 1));
            }
            if(stack.peek().getValue() == k){
                for(int i = 0; i < k; i++){
                    stack.pop();
                }
            }
        }
        
        StringBuilder sb = new StringBuilder();
        while(!stack.isEmpty()){
            sb.append(stack.pop().getKey());
        }

        return sb.reverse().toString();
    }
}

标签:1209,栈顶,整数,stack,II,sb,new,LeetCode
From: https://www.cnblogs.com/shixuanliu/p/17026858.html

相关文章

  • 【栈】LeetCode 1472. 设计浏览器历史记录
    题目链接1472.设计浏览器历史记录思路用栈history模拟网页的前进后退操作,用栈temp来暂时存储后退所退出的网页。代码classBrowserHistory{Stack<String>h......
  • [LeetCode] 2453. Destroy Sequential Targets
    Youaregivena 0-indexed array nums consistingofpositiveintegers,representingtargetsonanumberline.Youarealsogivenaninteger space.Youhave......
  • 代码随想录算法训练营第七天 |454.四数相加II 383. 赎金信 15. 三数之和 18. 四数之和
    454.四数相加II文章:代码随想录(programmercarl.com)视频:学透哈希表,map使用有技巧!LeetCode:454.四数相加II_哔哩哔哩_bilibili思路:首先定义一个unordered_map,key放a......
  • leetcode-653. 两数之和 IV - 输入二叉搜索树
    653.两数之和IV-输入二叉搜索树-力扣(Leetcode)用了迭代进行遍历二叉树,因为二叉搜索树的中序遍历是有序的,所以肯定左边大于右边,然后就可以用一个map来存放之前的数值,......
  • [LeetCode]015-三数之和
    >>>传送门题目给你一个整数数组nums,判断是否存在三元组[nums[i],nums[j],nums[k]]满足i!=j、i!=k且j!=k,同时还满足nums[i]+nums[j]+nums[k]==0......
  • leetcode-387-easy
    FirstUniqueCharacterinaStringGivenastrings,findthefirstnon-repeatingcharacterinitandreturnitsindex.Ifitdoesnotexist,return-1.Examp......
  • leetcode-414-easy
    ThirdMaximumNumberGivenanintegerarraynums,returnthethirddistinctmaximumnumberinthisarray.Ifthethirdmaximumdoesnotexist,returnthemaxim......
  • leetcode-563-easy
    BinaryTreeTiltGiventherootofabinarytree,returnthesumofeverytreenode'stilt.Thetiltofatreenodeistheabsolutedifferencebetweenthesum......
  • leetcode-349-easy
    IntersectionofTwoArraysGiventwointegerarraysnums1andnums2,returnanarrayoftheirintersection.Eachelementintheresultmustbeuniqueandyoum......
  • leetcode-350-easy
    IntersectionofTwoArraysIIGiventwointegerarraysnums1andnums2,returnanarrayoftheirintersection.Eachelementintheresultmustappearasmany......