Palindrome Partitioning

来源:互联网 发布:网络信息安全检查表 编辑:程序博客网 时间:2024/05/29 16:15

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"]  ]

思路:用DFS来做,加上判断是否是palindrome。

class Solution {public:    vector<vector<string>> partition(string s) {        vector<vector<string>> result;        if (s.empty()) return result;                vector<string> partition;        partitionUtil(result, partition, s, 0, s.size() - 1);    }        void partitionUtil(vector<vector<string>> &result, vector<string> &partition, string &s, int start, int end) {        if (start > end) {            result.push_back(partition);        }        else {            for (int i = start; i <= end; ++i) {                string str1 = s.substr(start, i - start + 1);                if (isPalindrome(str1)) {                    partition.push_back(str1);                    partitionUtil(result, partition, s, i+1, end);                    partition.pop_back();                }            }        }    }        bool isPalindrome(const string &str) {       int low = 0;        int high = str.length() -1;       while(low < high){           if (str[low] != str[high]) {               return false;           }                      low++;           high--;       }                return true;    }};


0 0
原创粉丝点击