美文网首页
38. Palindrome Partitioning

38. Palindrome Partitioning

作者: 时光杂货店 | 来源:发表于2017-03-17 20:20 被阅读9次

    题目

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

    解题之法

    class Solution {
    public:
        vector<vector<string>> partition(string s) {
            vector<vector<string> > ret;
            if(s.empty()) return ret;
            
            vector<string> path;
            dfs(0, s, path, ret);
            
            return ret;
        }
        
        void dfs(int index, string& s, vector<string>& path, vector<vector<string> >& ret) {
            if(index == s.size()) {
                ret.push_back(path);
                return;
            }
            for(int i = index; i < s.size(); ++i) {
                if(isPalindrome(s, index, i)) {
                    path.push_back(s.substr(index, i - index + 1));
                    dfs(i+1, s, path, ret);
                    path.pop_back();
                }
            }
        }
        
        bool isPalindrome(const string& s, int start, int end) {
            while(start <= end) {
                if(s[start++] != s[end--])
                    return false;
            }
            return true;
        }
    };
    

    相关文章

      网友评论

          本文标题:38. Palindrome Partitioning

          本文链接:https://www.haomeiwen.com/subject/qodynttx.html