Computer >> 컴퓨터 >  >> 프로그램 작성 >> C++

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.

주어진 문자열의 모든 순열을 인쇄할 수 있는 두 가지 방법이 있습니다.

회전()

우리가 사용할 첫 번째 방법은 회전 방법을 사용하는 것입니다. 이 방법에서는 문자열을 회전하는 데 사용되는 STL의 회전 기능을 사용하고 순열을 인쇄하는 데 재귀를 사용할 것입니다.

예시

위 방법에 대한 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

다음_순열

이제 우리는 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 기능과 그 사용법을 배웠습니다. 이 튜토리얼이 도움이 되기를 바랍니다.