Skip to content

Instantly share code, notes, and snippets.

@Zhomart
Last active October 7, 2015 20:03
Show Gist options
  • Save Zhomart/326171451a50c6941e8c to your computer and use it in GitHub Desktop.
Save Zhomart/326171451a50c6941e8c to your computer and use it in GitHub Desktop.
package main
import (
"bufio"
"fmt"
"os"
)
func Reverse(a []byte) {
n := len(a)
for j := 0; j < n/2; j++ {
tmp := a[j]
a[j] = a[n-j-1]
a[n-j-1] = tmp
}
}
func NextPerm(sPtr *string) string {
b := []byte(*sPtr)
n := len(b)
for i := n - 2; i >= 0; i-- {
if b[i] < b[i+1] {
// Find the last element that is greater than b[i]
nextMin := n - 1
for ; b[nextMin] <= b[i]; nextMin-- {
}
// swap i, nextMin
tmp := b[i]
b[i] = b[nextMin]
b[nextMin] = tmp
// reverse i+1 .. n
Reverse(b[i+1 : n])
return string(b)
}
}
return "no answer"
}
func main() {
in := bufio.NewReader(os.Stdin)
var t int
fmt.Fscanf(in, "%d\n", &t)
for ; t > 0; t-- {
var s string
fmt.Fscanf(in, "%s\n", &s)
fmt.Println(NextPerm(&s))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment