Maximum Swap

https://www.lintcode.com/problem/maximum-swap/description

public class Solution {
    /**
     * @param num: a non-negative intege
     * @return: the maximum valued number
     */
    public int maximumSwap(int num) {
        // Write your code here
        String s = String.valueOf(num);
        char[] chars = s.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            char aChar = chars[i];
            int min = getMin(chars, i);
            if (min != i) {
                chars[i] = chars[min];
                chars[min] = aChar;
                return Integer.parseInt(String.valueOf(chars));
            }
        }
        return num;
    }

    private int getMin(char[] chars, int i) {
        int index = i;
        for (int j = i + 1; j < chars.length; j++) {
            if (Character.compare(chars[j], chars[index]) >= 0) {
                index = j;
            }
        }
        return index;
    }
}

你可能感兴趣的:(Maximum Swap)