Pointing to Offer - Interview Question 28: Arrangement of Strings

arrangement of strings


Question: Input a string and print out all the permutations of the characters in the string. For example, if the string abc is input, all strings abc, acb, bac, bca, cab and cba that can be arranged by the strings a, b, and c are printed out.

Input: abc

Output: abc acb bac bca cab cba

Ideas: 1. Use one traversal to separate the problems.
2. For example, only consider what to put in the first character. For example, the first character can be put in a, b, and c.
3. Then consider the second and third characters when the first character is determined, and so on.

#include<iostream>
#include<vector>
#include<string>
using namespace std;

//这里是用vector做的,下面我再写一个用指针做的
vector<string> findAllString(string str, int index){
    vector<string> strTemp;
    vector<string> strVec;
    if (index == str.size() - 1){
        strVec.push_back(str);
    }
    for (int i = index+1; i < str.size(); i++){
        if (str[index + 1] != str[i] && i!=index+1){
            swap(str[index + 1], str[i]);
            strTemp = findAllString(str, index + 1);
            strVec.insert(strVec.end(), strTemp.begin(), strTemp.end());
            //计算完后,再交换回来
            swap(str[0], str[i]);
        }
    }
    return strVec;
}

//这里是用vector做的,下面我再写一个用指针做的
vector<string> Permutation(string str) {
    vector<string> strVec;
    vector<string> strTemp;
    for (int i = 0; i<str.size(); i++){
        //交换第1个字符和后面的字符的位置
        if (str[0] != str[i] && i!=0){
            swap(str[0], str[i]);
            strTemp = findAllString(str, 0);
            strVec.insert(strVec.end(), strTemp.begin(), strTemp.end());
            //计算完后,再交换回来
            swap(str[0], str[i]);
        }
    }
    return strVec;
}

//下面使用指针做一遍
//pStr表示字符串的地址,pBegin表示指针指向的位置
void Permutation(char *pStr,char *pBegin){
    if (*pBegin == '\0'){
        cout << pStr << endl;
    }
    char pTemp;
    int index = 0;
    for (char* ph=pBegin; *ph != '\0'; ph++){
        index++;
        //指针进行交换
        pTemp = *ph;
        *ph = *pBegin;
        *pBegin = pTemp;
        Permutation(pStr, pBegin + 1);
        //指针进行交换
        pTemp = *ph;
        *ph = *pBegin;
        *pBegin = pTemp;
    }
}

int main(){
    string str;
    vector<string> strVec;
    cin >> str;
    strVec = Permutation(str);
    system("pause");
    return 0;
}

//指针的用这个main:
int main(){
    //如果输入的是字符串型,即string时,是不会自动赋一个'\0'的
    char c[10] = { "aba" };
    //指针的题目话,还是有一个bug:如果字符是重复的话,就是会重复输出
    char *pStr = c;
    Permutation(pStr, pStr);
    system("pause");
    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325512267&siteId=291194637