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 =
return a string
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.
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() + ""; } }
相关文章推荐
- mysql查询正在执行的进程
- android自定义9宫格图片视图
- 缅甸维加斯开户网址:nob211.com 咨询热线:18206945156
- keepalived 安装
- C++调用C静态库,出现undefined reference to “” 的问题
- 【日志7.14】
- 缅甸维加斯赌场开户
- os x1
- Wood Cut
- 增强的页面元素
- 表单验证
- HTML5的新的表单属性
- HTML5新的Input类型
- HTML5音频
- HTML5视频
- Android 联系人数据库表详解
- Leetcode Factorial Trailing Zeroes
- drag and drop(拖拽)
- Leetcode Excel Sheet Column Number
- Leetcode Copy List with Random Pointer