使用STL的C++給定字串排列
字串的排列是指給定字串的字元以任何形式重新排列後形成的新字串。在本教程中,我們將討論如何使用C++的標準模板庫(STL)列印給定字串的所有排列,例如:
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的rotate函式。此方法將使用STL的rotate函式旋轉字串,並使用遞迴來列印排列。
示例
上述方法的C++程式碼
#include<bits/stdc++.h>
using namespace std;
void permutations(string s, string ans){
if(s.size() == 0) {
// when our string which needs to
//be rotated becomes empty then it means
//that our permutation is stored in ans
cout << ans << "\n";
return ;
}
for(int i = 0; i < s.size(); i++){
permutations(s.substr(1), ans + s[0]);
// we are adding the
// first character in our ans
// passing all elements from index 1 in our
// rotate string for next function.
rotate(s.begin(), s.begin()+1, s.end());
//rotating such that our second element becomes first
}
}
int main(){
string s = "ADT"; // given string
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"; // given string
sort(s.begin(), s.end()); // sorting the string
do{
cout << s << "\n"; // printing the permutations
}while(next_permutation(s.begin(), s.end())); // till next_permutations returns false
return 0;
}輸出
ADT ATD DAT DTA TAD TDA
在上面的程式中,我們對字串進行排序,然後藉助next_permutation函式列印所有可能的排列。
結論
在本教程中,我們使用C++中的STL列印了給定字串的所有可能的排列。我們還學習了此問題的C++程式以及一些重要的STL函式及其用途。希望本教程對您有所幫助。
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP