congr / world

2 stars 1 forks source link

LeetCode : 556. Next Greater Element III #510

Closed congr closed 5 years ago

congr commented 5 years ago

https://leetcode.com/problems/next-greater-element-iii/

image

congr commented 5 years ago
class Solution {
    public int nextGreaterElement(int n) {
        String s = String.valueOf(n);
        char[] c = s.toCharArray();

        int left = c.length - 2, right = c.length - 1;
        while (left >= 0 && c[left] >= c[left+1]) left--; // finding reversed position
        if (left == -1) return -1; // !!!

        while (right >= 0 && c[left] >= c[right]) right--;        
        swap(c, left, right);
        reverse (c, left+1);

        long val = Long.parseLong(new String(c));
        return val > Integer.MAX_VALUE ? -1 : (int)val;
    }

    void swap(char[] nums, int i, int j) {
        char temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }

    void reverse(char[] c, int start) {
        int end = c.length -1;

        while (start < end) {
            swap(c, start++, end--);
        }
    }
}