题目:
DJI 8.16第三题
解题思路:
贪心算法
https://leetcode-cn.com/problems/remove-k-digits/solution/yi-diao-kwei-shu-zi-by-leetcode/
代码:
package com.janeroad;
import java.util.LinkedList;
/**
* Created on 2020/8/16.
*
* [@author](https://my.oschina.net/arthor) LJN
*/
public class Test28 {
public static void main(String[] args) {
System.out.println(removeKdigits("71245323308", 4));
}
public static String removeKdigits(String num, int k) {
LinkedList<Character> stack = new LinkedList<Character>();
for(char digit : num.toCharArray()) {
while(stack.size() > 0 && k > 0 && stack.peekLast() > digit) {
stack.removeLast();
k -= 1;
}
stack.addLast(digit);
}
/* remove the remaining digits from the tail. */
for(int i=0; i<k; ++i) {
stack.removeLast();
}
// build the final string, while removing the leading zeros.
StringBuilder ret = new StringBuilder();
boolean leadingZero = true;
for(char digit: stack) {
if(leadingZero && digit == '0') continue;
leadingZero = false;
ret.append(digit);
}
/* return the final string */
if (ret.length() == 0) return "0";
return ret.toString();
}
}
来源:oschina
链接:https://my.oschina.net/u/4248053/blog/4498017