131. Palindrome Partitioning
来源:互联网 发布:linux cern 知乎 编辑:程序博客网 时间:2024/06/14 01:34
问题描述
Given a string s, partition s such that every substring of the partition is a palindrome.Return all possible palindrome partitioning of s.
For example, given s = “aab”,
Return
[
[“aa”,”b”],
[“a”,”a”,”b”]
]
解题思路
该问题给出一个字符串s,要求我们找出该字符串中所有是回文串的子字符串。对于该问题我们可以这样思考:对于这个字符串s,如果我们可以判断前n个字符是回文串,那我们可以直接考虑紧接在后面的字符串是否是回文串,于是这个问题被分解成了一个更小的问题。这道题更像一个分治法的题,将问题规模不断缩小,当然的遍历字符串的过程中进行回溯即可。我们需要另外一个辅助函数进行回文串的判断。
代码展示
#include<iostream>#include<string>#include<vector>using namespace std;class Solution {public: vector<vector<string> > partition(string s) { vector<string> path; vector<vector<string> > result; helper(s,0,path,result); return result; } void helper(string s,int pos,vector<string> & path,vector<vector<string> > & result) { if(pos==s.size()) { result.push_back(path); return ; } for(int i=pos;i<s.size();i++) { if(isPalindrome(s.substr(pos,i-pos+1))) //如果到此位置构成回文串 { path.push_back(s.substr(pos,i-pos+1)); helper(s,i+1,path,result); //从下个位置开始是否有回文串 path.pop_back(); } } } bool isPalindrome(string s) //判断字符串s是否是回文串函数 { int first=0; int end=s.size()-1; while(first<end) { if(s[first++]!=s[end--]) return false; } return true; }};int main(){ string s; cout<<"请输入字符串s:"; cin>>s; Solution solution; vector<vector<string> > result=solution.partition(s); int size = result.size(); for(int i=0;i<size;i++){ int size1=result[i].size(); cout<<"["; int j; for(j=0;j<size1-1;j++){ cout<<result[i][j]<<", "; } cout<<result[i][j]<<"]"<<endl; }}
运行结果展示
阅读全文
0 0
- 131. Palindrome Partitioning && 132. Palindrome Partitioning II
- LeetCode 131. Palindrome Partitioning
- [LeetCode]131.Palindrome Partitioning
- [Leetcode] 131. Palindrome Partitioning
- [leetcode] 131.Palindrome Partitioning
- 131. Palindrome Partitioning
- 131. Palindrome Partitioning
- 131. Palindrome Partitioning
- [LeetCode]131. Palindrome Partitioning
- 131. Palindrome Partitioning LeetCode
- 131. Palindrome Partitioning
- Leetcode 131. Palindrome Partitioning
- 131. Palindrome Partitioning
- 131. Palindrome Partitioning
- LeetCode 131. Palindrome Partitioning
- LeetCode *** 131. Palindrome Partitioning
- 131. Palindrome Partitioning
- LeetCode 131. Palindrome Partitioning
- java小细节不然很容易报错或者出逻辑问题得不到自己想要的。
- ARM的商业模式和ARM各种版本号区分
- 3ds Max导出OBJ的mtl贴图路径不正确
- 根据id分表
- SVN 使用简介及个人总结
- 131. Palindrome Partitioning
- C++之inline函数
- 如何远程操控另一台计算机
- A14_反射
- android inflate源码解析
- 53. Maximum Subarray
- JingS-3
- ACM大数模版
- Python ——优雅的解释型语言