hackerrank上的一道题——Bigger is Greater

hackerrank上的一道题——Bigger is Greater_第1张图片
hackerrank上的一道题——Bigger is Greater_第2张图片
题目描述

解题思路参考:https://www.nayuki.io/page/next-lexicographical-permutation-algorithm 具体代码如下:

    import java.util.Scanner;

    /**
     * Created by huliang on 16/7/25.
     */
    public class Solution {
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            int n = scanner.nextInt();
            for (int i = 0; i < n; i++) {
                String s = scanner.next();
                char[] chars = s.toCharArray();
                String result = nextPermutation(chars);
                if (result.length() == 0) {
                    System.out.println("no answer");
                } else {
                    System.out.println(result);
                }

            }
        }

        public static String nextPermutation(char[] array) {
            // Find non-increasing suffix
            int i = array.length - 1;
            while (i > 0 && array[i - 1] >= array[i])
                i--;
            if (i <= 0)
                return "";

            // Find successor to pivot
            int j = array.length - 1;
            while (array[j] <= array[i - 1])
                j--;
            char temp = array[i - 1];
            array[i - 1] = array[j];
            array[j] = temp;

            // Reverse suffix
            j = array.length - 1;
            String result = "";
            while (i < j) {
                temp = array[i];
                array[i] = array[j];
                array[j] = temp;
                i++;
                j--;
            }
            return String.valueOf(array);
        }
    }

你可能感兴趣的:(hackerrank上的一道题——Bigger is Greater)