📜  使用STL的字符串的词法等级

📅  最后修改于: 2021-04-29 18:02:38             🧑  作者: Mango

您将得到一个字符串,在按字典顺序排序的所有排列中找到其排名。

例子:

Input : str[] = "acb"
Output : Rank = 2

Input : str[] = "string"
Output : Rank = 598

Input : str[] = "cba"
Output : Rank = 6

我们已经讨论过找到字符串的词典顺序的解决方案

在本文中,我们使用STL函数“ next_permutation()”来生成给定字符串的所有可能排列,并且由于它按字典顺序提供了排列,我们将放置一个迭代器以查找每个字符串的等级。当我们的置换字符串与原始输入字符串相同时进行迭代时,我们从循环中中断,最后一次迭代的迭代器值是我们所需的结果。

// C++ program to print rank of 
// string using next_permute()
#include 
using namespace std;
   
// Function to print rank of string
// using next_permute()
int findRank(string str)
{
    // store original string
    string orgStr = str;
  
    // Sort the string in lexicographically
    // ascending order
    sort(str.begin(), str.end());
   
    // Keep iterating until
    // we reach equality condition
    long int i = 1;
    do {
        // check for nth iteration
        if (str == orgStr)
            break;
   
        i++;
    } while (next_permutation(str.begin(), str.end()));
   
    // return iterator value
    return i;
}
   
// Driver code
int main()
{
    string str = "GEEKS";
    cout << findRank(str);
    return 0;
}

输出:

25