https://www.lintcode.com/problem/remove-k-digits/description
public class Solution {
/**
* @param num: a string
* @param k: an integer
* @return: return a string
*/
public String removeKdigits(String num, int k) {
// write your code here
if (num.length() <= k) {
return "0";
}
char[] array = num.toCharArray();
StringBuilder stringBuilder = new StringBuilder();
int startIndex = 0;
// 最后的位数应该是
int finalLength = num.length() - k;
while (stringBuilder.length() < finalLength) {
// 已经有的位数是
int length = stringBuilder.length();
int remianlength = finalLength - length;
// 右边界是
int right = num.length() - remianlength;
char temp = array[startIndex];
startIndex++;
for (int i = startIndex; i <= right; i++) {
if (array[i] < temp) {
temp = array[i];
startIndex = i + 1;
}
}
stringBuilder.append(temp);
}
String s = stringBuilder.toString();
while (s.length() > 1 && s.startsWith("0")) {
s = s.substring(1);
}
return s;
}
}
网友评论