美文网首页
Remove K Digits

Remove K Digits

作者: Frank_Kivi | 来源:发表于2018-06-28 11:54 被阅读6次

    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;
        }
    }
    

    相关文章

      网友评论

          本文标题:Remove K Digits

          本文链接:https://www.haomeiwen.com/subject/rrrgyftx.html