402. Remove K Digits
Given a non-negative integer num represented as a string, remove k digits from the number so that the new number is the smallest possible.
Note:
- The length of num is less than 10002 and will be ≥ k.
- The given num does not contain any leading zero.
Example 1:
Input: num = "1432219", k = 3 Output: "1219" Explanation: Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest.
Example 2:
Input: num = "10200", k = 1 Output: "200" Explanation: Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes.
Example 3:
Input: num = "10", k = 2 Output: "0" Explanation: Remove all the digits from the number and it is left with nothing which is 0.
题目含义:给定的整数中删除k位后尽可能得到最小值
1 public String removeKdigits(String num, int k) { 2 Stack<Character> digs = new Stack<>(); 3 int length = num.length(); 4 if (k == 0) return num; 5 if (k == length) return "0"; 6 int i = 0; 7 while (i < length) { 8 9 while (k > 0 && !digs.isEmpty() && num.charAt(i) < digs.peek()) { 10 //保证顶上的元素小于等于num.charAt(i) 11 digs.pop(); 12 k--; //相当于删除一位较大的值 13 } 14 digs.push(num.charAt(i));//保证栈从顶到低的值是递减的 15 i++; 16 } 17 while (k > 0) { //k为数字还没有删除够,继续删除 18 digs.pop(); 19 k--; 20 } 21 StringBuilder sb = new StringBuilder(); 22 while (!digs.isEmpty()) { 23 sb.append(digs.pop()); //构成由高到底的字符串 24 } 25 sb.reverse();//翻转成由底到高的字符串,因为在push的时候是按照i顺序push的,所以反转后的字符串中每个字符的先后顺序和原来保持一致 26 while (sb.length() > 1 && sb.charAt(0) == '0') { 27 sb.deleteCharAt(0); 28 } 29 return sb.toString(); 30 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!