剑指offer—字符串的排列
2015-10-04 10:31
337 查看
华电北风吹
天津大学认知计算与应用重点实验室
日期:2015/10/4
题目描述
输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。 结果请按字母顺序输出。
输入描述:
输入一个字符串,长度不超过9(可能有字符重复),字符只包括大小写字母。
解析:每次寻找一个比当前字符串大1的字符串。规则很好找从最后一位寻找,若前一位比当前位大,往前移一位,知道发现有比当前位小的停止(若没发现,当前字符串已是最大,算法退出),然后在末尾这些排好序的字符中寻找比这个字符串大的最小的哪个放到这个字符串的位置,把剩下的字符串从小到大接到后面即可。
利用algorithm库里面的next_permutation函数。
自己写代码实现
天津大学认知计算与应用重点实验室
日期:2015/10/4
题目描述
输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。 结果请按字母顺序输出。
输入描述:
输入一个字符串,长度不超过9(可能有字符重复),字符只包括大小写字母。
解析:每次寻找一个比当前字符串大1的字符串。规则很好找从最后一位寻找,若前一位比当前位大,往前移一位,知道发现有比当前位小的停止(若没发现,当前字符串已是最大,算法退出),然后在末尾这些排好序的字符中寻找比这个字符串大的最小的哪个放到这个字符串的位置,把剩下的字符串从小到大接到后面即可。
利用algorithm库里面的next_permutation函数。
class Solution { public: vector<string> Permutation(string str) { vector<string> result; if (str == "") return result; sort(str.begin(), str.end()); result.push_back(str); while (next_permutation(str.begin(),str.end())) { result.push_back(str); } return result; } };
自己写代码实现
class Solution { public: vector<string> Permutation(string str) { vector<string> result; if (str == "") return result; sort(str.begin(), str.end()); result.push_back(str); if(str.length()==1) return result; while (Next(str)) { result.push_back(str); } return result; } bool Next(string &str) { int length = str.length(); int i = length - 2; while (i > 0 && str[i] >= str[i + 1]) { i--; } if ((i == 0) && (str[i] >= str[i + 1])) return false; int j = length - 1; while (str[j] <= str[i]) { j--; } string temp = str; str[i] = temp[j]; temp[j] = temp[i]; for (int k = i + 1; k < length; k++) str[k] = temp[length - k + i]; return true; } };
相关文章推荐
- LeetCode "Game of Life"
- jQuery插件Timelinr 实现时间轴特效
- 自定义tableview Header和Footer的样式
- META
- 剑指offer—二叉搜索树与双向链表
- jquery 实现输入邮箱时自动补全下拉提示功能
- React Native 开始
- HTML5学习之二:HTML5中的表单1
- ubuntu下安装node
- html5 自定义标签属性取值为undefined 笔记随记
- namenode无法启动,不报错
- js定时器timer
- 使用Ajax中的Json传输数据时,从后台查询的字段过滤方法。
- 【bzoj1016】【JSOI2008】【最小生成树计数】【dfs+最小生成树】
- The ratio of reported blocks 0.0000 has not reached the threshold 0.9990. Safe mode will be turned o
- Hadoop 报错be replicated to 0 nodes, instead of 1
- Could not buffer record
- ByteBuffer写入数组BufferUnderflowException异常
- A configuration error occurred during startup.Please verify the preference filed with the prompt
- hadoop异常“could only be replicated to 0 nodes, instead of 1” 解决