给定字符串S ,打印在字典上大于S的字符串S的排列。如果没有字符串的这种排列,则打印-1。
例子:
Input : BCA
Output : CAB, CBA
Explanation:
Here, S = “BCA”, and there are 2 strings “CAB, CBA” which are lexicographically greater than S.
Input : CBA
Output : -1
There is no string which is lexicographically greater than S, so the output is -1.
方法:为了解决上述问题,我们将使用STL。使用next_permuation()和prev_permutation()函数检查并按字典顺序排列更大的字符串。如果字符串较大,则打印它,否则打印-1。
下面是上述方法的实现:
// C++ program to print the lexicographically
// greater strings then the given string
#include
using namespace std;
// Function to print the lexicographically
// greater strings then the given string
void print_lexiStrings(string S)
{
// Condition to check if there is no
// string which is lexicographically
// greater than string S
if (!next_permutation(S.begin(), S.end()))
cout << "-1";
// Move to the previous permutation
prev_permutation(S.begin(), S.end());
// Iterate over all the
// lexicographically greater strings
while (next_permutation(S.begin(), S.end())) {
cout << S << "\n";
}
}
// Driver Code
int main()
{
string S = "ABC";
print_lexiStrings(S);
}
输出:
ACB
BAC
BCA
CAB
CBA