《剑指offer》字符串的排列
2016-07-19 20:32
501 查看
一、题目描述
输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串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; } };
相关文章推荐
- JavaScript基础知识整理
- angular的切换页面
- 回看JSP——解决提交form表单出现的乱码问题
- JSP注释格式
- HTML5编辑API之Range对象
- PHP文件数据传输用jQuery-ajax进行浏览器->服务器->数据文件->服务器->浏览器的数据传输($_POST,$_GET,json_encode(数组数据回应),json数据解析)
- yeoman-bower-grunt之间的关系
- fck实现htm在线编辑
- js实现ajax
- [Leetcode]289. Game of Life
- child伪类选择符入门(2)
- iOS之 改变日期显示样式
- 一个初级的前端工程师需要知道些什么?
- Nodejs从有门道无门菜鸟起飞教程。
- 基于ntkoocx.js的在线word编辑
- CSS,font-family,好看常用的中文字体
- 《剑指offer》二叉搜索树与双向链表
- 《剑指offer》复杂链表的复制
- 视差滚动Parallax
- 推荐大家使用的CSS书写规范、顺序