I am trying to implement a function similar to std::next_permutation(std::string w)
. Please see the code below for how I am doing this:
string biggerIsGreater(string w) {
// 1. Find the largest non-increasing suffix. This suffix already has the maximum permutation.
// 2. Assign the char before that as the pivot
// if there is no such char,
// then the whole string is non-increasing => no next permutation.
// 3. Swap the pivot with the smallest element in the suffix that is greater than the pivot itself.
// If there are multiple smallest char > pivot, then choose the rightmost one
// As this will keep the suffix non-increasing.
// 4. reverse the order of the suffix, so that it is now non-decreasing.
// This is the lowest next permutation.
// 1.
int suffix_start = (int)w.length()-1;
//single character has no next permutation:
if (suffix_start == 0) return "no answer";
// else keep decreasing suffix_start until the element is not > the previous.
while(w[suffix_start-1] <= w[suffix_start]) {
suffix_start--;
if(suffix_start==0) return "no answer";
}
// 2.
int pivot = suffix_start - 1;
// 3.
int smallest_char = (int)w.length()-1;
while(w[smallest_char] <= w[pivot]) smallest_char--;
if(w[smallest_char] == w[smallest_char-1]) while (w[smallest_char] != w[smallest_char-1]) smallest_char--;
swap(w[pivot], w[smallest_char]);
// 4.
reverse(w.begin() + pivot + 1, w.end());
return w;
}
However, this code appears to fail on strings like bb
. Please can you tell me where I have gone wrong?
If I print out w
after the reversal, I get this: (the first line is the number of test cases):
input:
5
ab
bb
hefg
dhck
dkhc
Then the program prints ba
(which means the first one worked) but nothing else is printed.
So the error is in dealing with bb
.
Note: My objective is to write this without std::next_permutation()
function from <algorithm>
.