My Accepted Java Solution


  • 0
    H
    public int maximumSwap(int num) {
            String origin=String.valueOf(num);
            char[] n=origin.toCharArray();
            Arrays.sort(n);
            StringBuilder sb=new StringBuilder(String.valueOf(n));
            n=sb.reverse().toString().toCharArray();
            int tag=-1;
            for(int i=0;i<n.length;i++)
                if(origin.charAt(i)!=n[i]){
                    tag=i;
                    break;
                }
            if(tag==-1)
                return num;
            char c=n[tag];
            int temp=-1;
            for(int i=origin.length()-1;i>=tag;i--)
                if(c==origin.charAt(i)){
                    temp=i;
                    break;
                }
            String result=swap(origin,tag,temp);
            return Integer.parseInt(result);
        }
        public String swap(String num,int i,int j){
            char[] n=num.toCharArray();
            char c=n[i];
            n[i]=n[j];
            n[j]=c;
            return String.valueOf(n);
        }
    

Log in to reply
 

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