标签:nbsp pre with str input app ringbuf repr bre
题目:
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:
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.
public String removeKdigits(String num, int k) {
/**
*用StringBuffer当做栈
*向栈中加入元素,如果新加入的元素小于栈顶元素弹出
*/
StringBuffer result = new StringBuffer();
int count = k, i;
for (i = 0; i < num.length(); ++i) {
while (result.length() > 0 && count > 0 && num.charAt(i) < result.charAt(result.length() - 1)) {
result.deleteCharAt(result.length() - 1);
count--;
}
result.append(num.charAt(i));
}
for (i=0;i<result.length();++i) { //删除结果中开始多余的0
if (result.charAt(i) != ‘0‘) {
break;
}
}
//计算结果字符串 //如果结果中全是0,防止数组过界
String re = result.substring(Math.min(i,result.length()-count), result.length() - count);
return re.equalsIgnoreCase("") ? "0" : re; //处理结果为空的情况
}
标签:nbsp pre with str input app ringbuf repr bre
原文地址:http://www.cnblogs.com/liulikecp3/p/7421302.html