402:移掉K位数字(未完成)

This commit is contained in:
huangge1199@hotmail.com 2021-04-25 09:10:55 +08:00
parent e680e575eb
commit 29d4f6313e
3 changed files with 131 additions and 1 deletions

View File

@ -0,0 +1,97 @@
//给定一个以字符串表示的非负整数 num移除这个数中的 k 位数字使得剩下的数字最小
//
// 注意:
//
//
// num 的长度小于 10002 k
// num 不会包含任何前导零
//
//
// 示例 1 :
//
//
//输入: num = "1432219", k = 3
//输出: "1219"
//解释: 移除掉三个数字 4, 3, 2 形成一个新的最小的数字 1219
//
//
// 示例 2 :
//
//
//输入: num = "10200", k = 1
//输出: "200"
//解释: 移掉首位的 1 剩下的数字为 200. 注意输出不能有任何前导零
//
//
// 示例 3 :
//
//
//输入: num = "10", k = 2
//输出: "0"
//解释: 从原数字移除所有的数字剩余为空就是0
//
// Related Topics 贪心算法
// 👍 556 👎 0
package leetcode.editor.cn;
import java.util.Stack;
//402:移掉K位数字
public class RemoveKDigits {
public static void main(String[] args) {
//测试代码
Solution solution = new RemoveKDigits().new Solution();
//1219
System.out.println(solution.removeKdigits("1432219", 3));
//200
System.out.println(solution.removeKdigits("10200", 1));
//0
System.out.println(solution.removeKdigits("10", 2));
//0
System.out.println(solution.removeKdigits("10", 1));
//11
System.out.println(solution.removeKdigits("112", 1));
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public String removeKdigits(String num, int k) {
if (num.length() == k) {
return "0";
}
Stack<Character> stack = new Stack<>();
int remove = 0;
int i = 0;
for (; i < num.length() - 1; i++) {
while (i + 1 < num.length() && num.charAt(i) > num.charAt(i + 1) && remove < k) {
num = num.substring(i + 1);
remove++;
while (!stack.isEmpty() && i + 1 < num.length() && stack.peek() > num.charAt(i + 1) && remove < k) {
stack.pop();
remove++;
}
}
if (remove == k) {
break;
}
if (i < num.length()) {
stack.push(num.charAt(i));
}
}
while (!stack.isEmpty()) {
num = stack.pop() + num;
}
if (remove < k) {
num = num.substring(0, num.length() - k + remove);
}
while (num.length() > 1 && num.startsWith("0")) {
num = num.substring(1);
}
return num;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}

View File

@ -0,0 +1,33 @@
<p>给定一个以字符串表示的非负整数&nbsp;<em>num</em>,移除这个数中的 <em>k </em>位数字,使得剩下的数字最小。</p>
<p><strong>注意:</strong></p>
<ul>
<li><em>num</em> 的长度小于 10002 且&nbsp;&ge; <em>k。</em></li>
<li><em>num</em> 不会包含任何前导零。</li>
</ul>
<p><strong>示例 1 :</strong></p>
<pre>
输入: num = &quot;1432219&quot;, k = 3
输出: &quot;1219&quot;
解释: 移除掉三个数字 4, 3, 和 2 形成一个新的最小的数字 1219。
</pre>
<p><strong>示例 2 :</strong></p>
<pre>
输入: num = &quot;10200&quot;, k = 1
输出: &quot;200&quot;
解释: 移掉首位的 1 剩下的数字为 200. 注意输出不能有任何前导零。
</pre>
<p>示例<strong> 3 :</strong></p>
<pre>
输入: num = &quot;10&quot;, k = 2
输出: &quot;0&quot;
解释: 从原数字移除所有的数字剩余为空就是0。
</pre>
<div><div>Related Topics</div><div><li></li><li>贪心算法</li></div></div>\n<div><li>👍 556</li><li>👎 0</li></div>

File diff suppressed because one or more lines are too long