给定一个字符串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
如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live