剑指Offer——面试题28:字符串的排列
2018-03-24 00:16
483 查看
字符串的排列
题目:输入一个字符串,打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符串a、b、c所能排列出的所有字符串abc、acb、bac、bca、cab和cba。输入:abc
输出:abc acb bac bca cab cba
思路:1、用一次遍历,将问题分开来做2、比如只考虑第一个字符放什么,比如第一个字符可以放a,放b,放c。
3、然后再第一个字符确定的情况下考虑第2、第3个字符,依次类推即可
#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]); } } retu 4000 rn 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; }
相关文章推荐
- 剑指offer面试题28:字符串的排列
- 剑指offer面试题28:字符串的排列
- 【剑指Offer学习】【面试题28 :字符串的排列】
- 剑指offer-面试题28 字符串的排列
- 剑指offer之面试题28:字符串的排列
- 剑指offer-面试题28:字符串的排列
- 剑指offer 面试题28:字符串的排列
- 【剑指offer】面试题28:字符串的排列
- 剑指Offer面试题28字符串的排列组合(递归和栈)
- 剑指offer 面试题28—字符串的排列
- 剑指offer————面试题28(字符串排列)
- 剑指Offer:面试题28 字符串的排列
- 剑指Offer面试题28(java版):字符串的排列
- 剑指offer 面试题28 字符串全排列
- 剑指offer-面试题28.字符串的排列
- 剑指offer面试题28: 字符串的排列
- 剑指Offer_面试题28_字符串的排列
- 剑指offer-面试题28-字符串的排列
- 剑指offer面试题28-字符串的排列
- 剑指Offer----面试题28:字符串的排列 & 去重