码迷,mamicode.com
首页 > 其他好文 > 详细

lintcode-medium-Delete Digits

时间:2016-03-18 13:29:04      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:

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

 

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

return a string "12"

 

贪心算法

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) {
        // write your code here
        
        if(A == null || A.length() == 0)
            return A;
        
        String str = A;
        
        for(int i = 0; i < k; i++){
            int index = 0;
            for(; index < str.length() - 1; index++){
                if(str.charAt(index) > str.charAt(index + 1))
                    break;
            }
            
            str = str.substring(0, index) + str.substring(index + 1);
        }
        
        while(str.charAt(0) == ‘0‘)
            str = str.substring(1);
        
        return str;
    }
}

 

lintcode-medium-Delete Digits

标签:

原文地址:http://www.cnblogs.com/goblinengineer/p/5291624.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!