Share my simple java solution


  • 0
    S
    class Solution {
        public int maximumSwap(int num) {
            char[] s = String.valueOf(num).toCharArray();
            int[] record = new int[10];
            for(int i = 0; i < s.length; i++){
                record[s[i] - '0'] = i;
            }
            
            for(int i = 0; i < s.length; i++){
                int digit = s[i] - '0';
                for(int j = 9; j > digit; j--){
                    if(record[j] > i){
                        char temp = s[i];
                        s[i] = s[record[j]];
                        s[record[j]] = temp;
                        return Integer.valueOf(new String(s));
                    }
                }
            }
            
            return num;
                   
            
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.