Monotone Increasing Digits

题目
Given a non-negative integer N, find the largest number that is less than or equal to N with monotone increasing digits.

(Recall that an integer has monotone increasing digits if and only if each pair of adjacent digits x and y satisfy x <= y.)

答案

最蠢的做法,不用想也知道会TLE。但是可以先写出来测试几个例子来找规律

class Solution {
    private boolean isIncreasing(int x) {
        int r = x % 10;
        x = x / 10;
        while(x != 0) {
            if(r < (x % 10)) return false;
            r = x % 10;
            x = x / 10;
        }
        return true;
    }
    public int monotoneIncreasingDigits(int N) {
        for(int i = N; i >= 0; i--) {
            if(isIncreasing(i)) return i;
        }
        return 0;
    }
}

测试几个例子之后,正确答案如下

class Solution {
    public int monotoneIncreasingDigits(int N) {
        StringBuilder strN = new StringBuilder(Integer.toString(N));
        char c;
        
        for(int i = strN.length() - 1; i >= 0; i--) {
            // Check if 'monotone increasing' is violated
            int curr_digit = Integer.parseInt(Character.toString(strN.charAt(i)));
            int left_digit = 0;
            if(i > 0)
                left_digit = Integer.parseInt(Character.toString(strN.charAt(i - 1)));
            
            // Suppose violation happens at x y in the number abcd[xy]efg
            // Among the digits in a,b,c,d,x, we need to find a number, subtract 1, and set all digits on its right to '9', which
            // should be done without causing another violation
            
            if(left_digit > curr_digit) {
                for (int j = i - 1; j >= 0; j--) {
                    int left = Integer.parseInt(Character.toString(strN.charAt(j)));
                    int left2 = 0;
                    if (j > 0)
                        left2 = Integer.parseInt(Character.toString(strN.charAt(j - 1)));
                    if (left2 <= left - 1) {
                        c = Character.forDigit(Integer.parseInt(Character.toString(strN.charAt(j))) - 1, 10);
                        strN.setCharAt(j, c);
                        for (int k = j + 1; k < strN.length(); k++)
                            strN.setCharAt(k, '9');
                        break;
                    }
                }
            }
        }
        return Integer.parseInt(strN.toString());
    }
}

你可能感兴趣的:(Monotone Increasing Digits)