zoukankan      html  css  js  c++  java
  • May LeetCoding Challenge13 之 单调栈

    所谓单调栈,即栈中的元素单调递增 或 单调递减

    本题用单调栈将数组维护成一个单调递增的集合。用k记录删除的元素个数。

    特别注意三点:

    1.如果num本身为递增序列,需要从从栈中弹出k个元素。

    2.需要删除队头为0的元素,可以初始化一个为true的bool型变量,一旦开始的头部不等于0,bool型变量为false。

    3.如果长度为0,返回"0"。

    JAVA

    class Solution {
        public String removeKdigits(String num, int k) {
            LinkedList<Character> stack = new LinkedList<>();
            StringBuilder res = new StringBuilder();
            for(char c: num.toCharArray()){
                while(k>0 && stack.size()>0 && stack.getLast() > c){
                    stack.removeLast();
                    k--;
                }
                stack.addLast(c);
            }
            for(int i = 0; i < k; i++){
                stack.removeLast(); // "11112" 1 针对这种输入,本身为递增序列,从后面删除k个数
            }
            boolean leadingZero = true; // "10000200" 1 针对这种输入。!!!删除前面为0的方法
            for(char c: stack){
                if(leadingZero && c == '0') continue;
                leadingZero = false; 
                res.append(c);
            }
            if(res.length() == 0) return "0"; //针对"10" 1 这种输入。
            return res.toString();
        }
    }

    Python3

    class Solution:
        def removeKdigits(self, num: str, k: int) -> str:
            stack = []
            res = ""
            for c in num:
                while k and stack and stack[-1] > c:
                    stack.pop()
                    k -= 1
                stack.append(c)
            for i in range(k):
                stack.pop()
            leadingZero = True
            for c in stack:
                if leadingZero and c == '0':
                    continue
                leadingZero = False
                res += c
            if len(res) == 0:
                return "0"
            return res
  • 相关阅读:
    动态传参
    函数的介绍
    文件的操作
    send email with formatted table
    minimize and close window with customed winform
    python algorithm
    something important about docker
    book list
    which language is suitable for what to do
    Find Duplicate Items in list fast
  • 原文地址:https://www.cnblogs.com/yawenw/p/12884837.html
Copyright © 2011-2022 走看看