Skip to content

Instantly share code, notes, and snippets.

@arcesino
Created March 14, 2016 03:04
Show Gist options
  • Save arcesino/9b57baf9a506978917e4 to your computer and use it in GitHub Desktop.
Save arcesino/9b57baf9a506978917e4 to your computer and use it in GitHub Desktop.
Next lexicographically word
def makeItLarge(inputs) {
inputs.collect { input ->
nextLexicographically(input)
}
}
def nextLexicographically(input) {
def queue = new java.util.PriorityQueue<Character>()
def a = input.toCharArray()
def pivot = -1
def i
for (i = a.length - 1; i > 0 && pivot == -1; i--) {
if (a[i] > a[i - 1]) {
pivot = i - 1;
queue.offer(a[i - 1])
}
queue.offer(a[i]);
}
if (pivot == -1) return "no answer";
def target = a[pivot];
while(queue.size() > 0) {
def next = queue.poll()
if (next > target) {
a[pivot] = next;
while(queue.size() > 0) a[i++] = queue.poll();
} else {
a[i++] = queue.poll();
}
}
return new String(a);
}
makeItLarge(["abcde", "edcba", "cacba"])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment