Concise Java Solution - Equivalent to Next Greater Permutation


  • 2
    public int nextGreaterElement(int num) {
        String n = Integer.toString(num);
        for (int i=n.length()-2;i>=0;i--) {
            if (n.charAt(i) >= n.charAt(i+1)) continue;
            for (int j=n.length()-1;j>i;j--) {
                if (n.charAt(i) >= n.charAt(j)) continue;
                try {
                    return Integer.parseInt(n.substring(0,i) + n.charAt(j) 
                           + new StringBuilder(n.substring(i+1, j) + n.charAt(i) + n.substring(j+1)).reverse().toString()); 
                } catch(Exception e) { return -1; }
            }
        }
        return -1;
    }
    

Log in to reply
 

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