解題思路參考: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);
}
}