Blog Archive

Permutations of a given string

 Permutations of a given string 

Q - Permutations of a given string

Given a string S. The task is to print all permutations of a given string.

Input:
The first line of input contains an integer T, denoting the number of test cases. Each test case contains a single string in capital letter.

Output:
For each test case, print all permutations of a given string with single space and all permutations should be in lexicographically increasing order.

Constraints:
1 ≤ T ≤ 10
1 ≤ size of string ≤ 5

Example:
Input:
2
ABC
ABSG

Output:
ABC ACB BAC BCA CAB CBA 
ABGS ABSG AGBS AGSB ASBG ASGB BAGS BASG BGAS BGSA BSAG BSGA GABS GASB GBAS GBSA GSAB GSBA SABG SAGB SBAG SBGA SGAB SGBA

Explanation:
Testcase 1:
 Given string ABC has permutations in 6 forms as ABC, ACB, BAC, BCA, CAB and CBA .


SOLUTION

#include < iostream >
    using namespace std;

void permutation(string sint i){
    //base Case
    if (s[i] == '\0') {
        cout << s << " ";
        return;
    }
    //recursive case
    for (int j = is[j] != '\0'j++) {
        swap(s[i], s[j]);
        permutation(si + 1);
        swap(s[i], s[j]);
    }
}
int main()
{
    //code
    int tcin >> t;
    while (t--) {

        string S;
        cin >> S;
        permutation(S0);
        cout << endl;
    }

    return 0;
}


Data Structures and Algorithm-String Data Structure


5 comments:

Recent Post

Sort an array of 0s, 1s and 2s

  Sort an array of 0s, 1s and 2s- Data Structures   Sort an array of 0s, 1s and 2s- Data Structures Given an array of size N containing onl...