Palindrome Partitioning学习

来源:互联网 发布:上课玩手机神器淘宝 编辑:程序博客网 时间:2024/06/11 05:24
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"]
  ]

http://oj.leetcode.com/problems/palindrome-partitioning/

题意: 对输入的字符串划分为一组回文字符串。

如例子   aab    分成了(1)aa  ,b;(2)a ,a,  b

采用类似字符串全排列的方法,采用深度优先算法dfs,边遍历边判断

C++代码

void p(string str, vector<string>&path, vector<vector<string>>&res){if (str.size() < 1){res.push_back(path);return;}for (int i = 0; i<str.size(); i++)//DFS{int begin = 0;int end = i;while (begin < end){//判断是否为回文的过程if (str[begin] == str[end]){begin++;end--;}elsebreak;}if (begin >= end){path.push_back(str.substr(0, i + 1));p(str.substr(i + 1), path, res);path.pop_back();}}}vector<vector<string>> partition(string str) {vector<vector<string>>res;vector<string>path;p(str, path, res);return res;}int main(){string s1 = "aab";vector<vector<string>> res=partition(s1);for (vector<vector<string>>::iterator iter = res.begin(); iter != res.end();iter++){vector<string> d = *iter;for (vector<string>::iterator iter1 = d.begin(); iter1 != d.end(); iter1++){cout << *iter1 << endl;}}return 0;}


结果如图



0 0
原创粉丝点击