|
| 1 | +// next permutation problems, https://www.nayuki.io/page/next-lexicographical-permutation-algorithm |
| 2 | +'use strict'; |
| 3 | + |
| 4 | +const fs = require('fs'); |
| 5 | + |
| 6 | +process.stdin.resume(); |
| 7 | +process.stdin.setEncoding('utf-8'); |
| 8 | + |
| 9 | +let inputString = ''; |
| 10 | +let currentLine = 0; |
| 11 | + |
| 12 | +process.stdin.on('data', inputStdin => { |
| 13 | + inputString += inputStdin; |
| 14 | +}); |
| 15 | + |
| 16 | +process.stdin.on('end', _ => { |
| 17 | + inputString = inputString.replace(/\s*$/, '') |
| 18 | + .split('\n') |
| 19 | + .map(str => str.replace(/\s*$/, '')); |
| 20 | + |
| 21 | + main(); |
| 22 | +}); |
| 23 | + |
| 24 | +function readLine() { |
| 25 | + return inputString[currentLine++]; |
| 26 | +} |
| 27 | + |
| 28 | +// Complete the biggerIsGreater function below. |
| 29 | +function biggerIsGreater(array) { |
| 30 | + array = array.split(''); |
| 31 | + // Find non-increasing suffix |
| 32 | + var i = array.length - 1; |
| 33 | + while (i > 0 && array[i - 1] >= array[i]) |
| 34 | + i--; |
| 35 | + if (i <= 0) |
| 36 | + return "no answer"; |
| 37 | + |
| 38 | + // Find successor to pivot |
| 39 | + var j = array.length - 1; |
| 40 | + while (array[j] <= array[i - 1]) |
| 41 | + j--; |
| 42 | + var temp = array[i - 1]; |
| 43 | + array[i - 1] = array[j]; |
| 44 | + array[j] = temp; |
| 45 | + |
| 46 | + // Reverse suffix |
| 47 | + j = array.length - 1; |
| 48 | + while (i < j) { |
| 49 | + temp = array[i]; |
| 50 | + array[i] = array[j]; |
| 51 | + array[j] = temp; |
| 52 | + i++; |
| 53 | + j--; |
| 54 | + } |
| 55 | + return array.join(''); |
| 56 | +} |
| 57 | + |
| 58 | +function main() { |
| 59 | + const ws = fs.createWriteStream(process.env.OUTPUT_PATH); |
| 60 | + |
| 61 | + const T = parseInt(readLine(), 10); |
| 62 | + |
| 63 | + for (let TItr = 0; TItr < T; TItr++) { |
| 64 | + const w = readLine(); |
| 65 | + |
| 66 | + let result = biggerIsGreater(w); |
| 67 | + |
| 68 | + ws.write(result + "\n"); |
| 69 | + } |
| 70 | + |
| 71 | + ws.end(); |
| 72 | +} |
0 commit comments