您的位置:首页 > 其它

Delete Digits

2016-07-15 05:15 381 查看
Given string A representative a positive integer which has N digits, remove any k digits of the number, the remaining digits are arranged according to the original order to become a new positive integer.

Find the smallest integer after remove k digits.

N <= 240 and k <= N,

Example

Given an integer A =
"178542"
, k =
4


return a string
"12"


Analysis:

When take current number n from string A, we need to compare the last digit we have in the new string, if n is greater than the last number in the new string, we do nothing. However, if n is less than the last digit in the new string, should we replace it? we can if we have

newString.length() + A.length() - p > A.length() - k.

public class Solution {
/**
*@param A: A positive integer which has N digits, A is a string.
*@param k: Remove k digits.
*@return: A string
*/
public String DeleteDigits(String A, int k) {

if (A == null || A.length() == 0 || k <= 0) return A;
if (A.length() == k) return "";

StringBuilder sb = new StringBuilder();
sb.append(A.charAt(0));

for (int p = 1; p < A.length(); p++) {
//这题关键的部分是如果当前这个数比前一个数小,我们就一定要把当前这个数替换掉前一个数。因为这样我们得到的数就一定更小。
// 但是也不是可以无限替换,我们得保证A后面部分的substring长度+当前sb的长度 >= A.length() - k
while (sb.length() >= 1 && A.charAt(p) < sb.charAt(sb.length() - 1) && sb.length() > p - k) {
sb.deleteCharAt(sb.length() - 1);
}
if (sb.length() < A.length() - k) {
sb.append(A.charAt(p));
}
}
int i = 0;
// remove the extra 0 at the beginning
while(sb.length() > 0 && sb.charAt(0) == '0') {
sb.deleteCharAt(0);
}

return sb.toString() + "";
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: