使用 STL 的给定字符串的 C++ 排列

当给定字符串的字符以任何形式重新排列时,就会形成字符串的排列。在本教程中,我们将讨论如何使用 C++ 的标准模板库打印给定字符串的所有排列,例如

Input : s = “ADT”

Output : “ADT”, “ATD”, “DAT”, “DTA”, “TAD”, “TDA”

Explanation : In the given output as you can see all the string are made up of same three character present in our string and are just rearranged thus they fit in the definition of a permutation of a string now there is one more thing to note these are all the permutations possible of string s.

有两种方法可以打印给定字符串的所有排列

Rotate()

我们要使用的第一种方法是使用旋转方法。在这个方法中,我们将使用 STL 的旋转函数,它用于旋转我们的字符串,我们将使用递归来打印排列。

示例

上述方法的 C++ 代码 

#include<bits/stdc++.h>
using namespace std;
void permutations(string s, string ans){
    if(s.size() == 0) {
// 当我们的字符串需要
//被旋转变成空然后这意味着
//我们的排列存储在 ans 中
        cout << ans << "\n";
        return ;
    }
    for(int i = 0; i < s.size(); i++){
        permutations(s.substr(1), ans + s[0]);
        // 我们正在添加
        // 我们的回答中的第一个字符
        // 在我们的索引 1 中传递所有元素
        // 为下一个函数旋转字符串。
        rotate(s.begin(), s.begin()+1, s.end());
        //旋转使得我们的第二个元素成为第一个
    }
}
int main(){
    string s = "ADT"; // 给定的字符串
    permutations(s, "");
    return 0;
}
输出结果
ADT
ATD
DTA
DAT
TAD
TDA

Next_Permutation

现在我们将使用STL的另一个函数,即next_Permutation,顾名思义,这个函数的返回轮是这个字符串的下一个排列是否存在。如果否,则返回false。

如您所知,此函数检查下一个排列;因此,我们首先需要按字典顺序对字符串进行排序,以便获得所有可能的排列。

示例

上述方法的 C++ 代码

#include<bits/stdc++.h>
using namespace std;
int main(){
    string s = "ADT"; // 给定的字符串
    sort(s.begin(), s.end()); // 对字符串进行排序
    do{
        cout << s << "\n"; // 打印排列
    }while(next_permutation(s.begin(), s.end())); // 直到 next_permutations 返回 false
    return 0;
}
输出结果
ADT
ATD
DAT
DTA
TAD
TDA

在上面的程序中,我们对字符串进行排序,然后在 next_permutation 函数的帮助下,我们打印出所有可能的排列。

结论

在本教程中,我们在 C++ 中使用 STL 的帮助打印给定字符串的所有可能排列。我们还学习了解决这个问题的 C++ 程序和一些基本的 STL 函数及其用法。我们希望本教程对您有所帮助。