其他分享
首页 > 其他分享> > 556. Next Greater Element III

556. Next Greater Element III

作者:互联网

This is a similiar problem with https://www.cnblogs.com/feiflytech/p/15862432.html

The only differences are:

1. If no larger number can be returned, this problem return -1

2. Need to judge whether the result number is largen then Integer.MAX_VALUE.

class Solution {
    public int nextGreaterElement(int n) {
        String s = String.valueOf(n);
        char[] cs = s.toCharArray();
        int last = cs[cs.length-1];
        int index = 0;
        for(int i=cs.length-1;i>0;i--){
            if(cs[i]>cs[i-1]){
                index = i;
                break;
            }
        }
        
        if(index==0)
            return -1;
        for(int i=cs.length-1;i>=index;i--){
            if(cs[i]>cs[index-1])
            {
                swap(cs, i, index-1);
                break;
            }
        }
        
        reverse(cs, index, cs.length-1);
        s = String.valueOf(cs);
        long res = Long.valueOf(s);
        if(res>Integer.MAX_VALUE)
            return -1;
        return (int)res;
    }
    
    private void swap(char[] cs, int i, int j){
        char temp = cs[i];
        cs[i]=cs[j];
        cs[j]=temp;
    }
    
    private void reverse(char[] cs, int i, int j){
        while(i<j){
            swap(cs, i++, j--);
        }
    }
}

 

标签:index,return,Greater,int,556,char,length,cs,III
来源: https://www.cnblogs.com/feiflytech/p/16169378.html