《剑指offer》字符串的排列
来源:互联网 发布:人类文明史图鉴淘宝 编辑:程序博客网 时间:2024/05/16 01:51
一、题目描述
输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。 结果请按字母顺序输出
二、输入描述
输入一个字符串,长度不超过9(可能有字符重复),字符只包括大小写字母。
三、输出描述
所能排列出来的所有字符串。结果请按字母顺序输出
四、牛客网提供的框架
class Solution {public: vector<string> Permutation(string str) { }};
五、解题思路
1、逐个字符插入,生成新的字符串
2、去掉相同的字符串
3、排序
对于步骤1、2:
例如:“abcc”逐个字符处理
vector vt
1)“a”进入vt
2)“b”跟vt中所有字符串组成新的字符串(“b”插入以前字符串不同的位置),”a”出列表,“b”插入“a”的不同位置得到的新字符串有:
“ab”,”ba”,都进入vt中()
3)对vt中的字符串检查是否有相同的字符串(没有)
4)“c”跟vt中所有字符串组成新的字符串:
“abc”,”acb”,”cab”;”bac”,”bca”,”cba”先后进入vt中。
5)对vt去重
6)“c”跟vt中所有字符串组成新的字符串:
“abcc”,”abcc”,”acbc”,”cabc”;
“acbc”,”accb”,”accb”,”cacb”;
“cabc”,”cacb”,”ccab”,”ccab”;
“bacc”,”bacc”,”bcac”,”cbac”;
“bcac”,”bcca”,”bcca”,”cbca”;
“cbac”,”cbca”,”ccba”,”ccba”;
进入vt中。
7)对vt去重、排序:
abcc
acbc
accb
bacc
bcac
bcca
cabc
cacb
cbac
cbca
ccab
ccba
六、代码
#include<iostream>#include<vector>#include<string>#include<queue>using namespace std;class Solution {public: vector<string> Permutation(string str) { vector<string> vt; int leng = str.size(); if(leng <= 0) return vt; string temp = ""; temp += str[0]; vt.push_back(temp); for(int i = 1; i < leng; i++) { string s = ""; s += str[i]; vector<string> tempQu; while(vt.size()>0) //逐个字符插入 { temp = vt.back(); for(int index = 0; index <= temp.size(); index++) //向字符串temp中各个位置插入s,生成不同的字符串 { string newStr = temp.substr(0, index); //使用拼接的方法 newStr += s; newStr += temp.substr(index, temp.size()-index); tempQu.push_back(newStr); } vt.pop_back(); } /* *去掉vector中相同的字符串 */ vt.clear(); for(int j = 0; j < tempQu.size(); j++) { string currStr = tempQu[j]; int k; for(k = 0; k < vt.size(); k++) { if(vt[k] == currStr) break; } if(k >= vt.size()) vt.push_back(currStr); } } vt = sortStr(vt); return vt; } /* *插入排序 */ vector<string> sortStr(vector<string> str) { for(int i = 1; i < str.size(); i++) { string temp = str[i]; int j = i - 1; while(j >= 0 && str[j] > temp) { str[j+1] = str[j]; j--; } str[j+1] = temp; } return str; }};
- 【剑指offer】字符串的排列
- 剑指offer--字符串的排列
- 《剑指offer》字符串的排列
- 【剑指Offer】字符串的排列
- 剑指offer--字符串的排列
- 剑指offer:字符串的排列
- 剑指offer:字符串的排列
- 剑指offer:字符串的排列
- [剑指offer]字符串的排列
- 《剑指offer》-字符串的排列
- 剑指offer|字符串的排列
- 【剑指offer】字符串的排列
- 《剑指offer》字符串的排列
- 剑指Offer:字符串的排列
- 【剑指offer】字符串的排列
- 剑指offer-字符串的排列
- 剑指offer 字符串的排列
- 剑指offer 字符串的排列
- TOJ 3777.Function Problem(三分基础题目)
- include < bits / stdc++ .h>
- 题目1043:Day of Week
- tomcat从下载到使用
- linux下安装配置jenkins
- 《剑指offer》字符串的排列
- 81. Search in Rotated Sorted Array II
- UVA-10474 Where is the Marble?
- 青蛙跳台阶问题
- POJ 2369Permutations
- hdoj--1862 EXCEL排序(sort+结构体)
- * **ACM错误总结
- restful--spring
- linux常用的一些命令(一)