程序员笔试&&面试经验

Leetcode. 回文字符串的分割和最少分割数

2017-03-16  本文已影响1088人  周肃

Q1: 回文字符串的分割

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

算法
回溯法.

以字符串 "ababc" 为例.

实现

class Solution {
public:
    vector<vector<string>> partition(string s) {
        std::vector<std::vector<std::string> > results;
        std::vector<std::string> res;
        dfs(s, 0, res, results);
        return results;
    }
private:
    void dfs(std::string& s, int startIndex,
            std::vector<std::string> res,
            std::vector<std::vector<std::string> >& results)
    {
        if (startIndex >= s.length())
        {
            results.push_back(res);
        }
        for (int i = startIndex; i < s.length(); ++i)
        {
            int l = startIndex;
            int r = i;
            while (l <= r && s[l] == s[r]) ++l, --r;
            if (l >= r)
            {
                res.push_back(s.substr(startIndex, i - startIndex + 1));
                dfs(s, i + 1, res, results);
                res.pop_back();
            }
        }
    }
};

Q2 回文字符串的最少分割数

Given a string s, partition s such that every substring of the partition is a palindrome.
Return the minimum cuts needed for a palindrome partitioning of s.

For example, given s = "aab",  
Return 1 since the palindrome partitioning 
["aa","b"] could be produced using 1 cut.

算法
Calculate and maintain 2 DP states:

实现

class Solution {

public:
    int minCut(std::string s) {
        int len = s.length();
        int minCut = 0;
        bool isPalindrome[len][len] = {false};
        int dp[len + 1] = {INT32_MAX};                                                                                                                
        dp[len] = -1;
        for (int leftIndex = len - 1; leftIndex >= 0; --leftIndex)
        {
            for (int midIndex = leftIndex; midIndex <= len - 1; ++midIndex)
            {
                if ((midIndex - leftIndex < 2 || isPalindrome[leftIndex + 1][midIndex -1])
                   && s[leftIndex] == s[midIndex])
                {
                    isPalindrome[leftIndex][midIndex] = true;
                    dp[leftIndex] = std::min(dp[midIndex + 1] + 1, dp[leftIndex]);
                }
            }
            std::cout << leftIndex << ": " << dp[leftIndex] << std::endl;
        }
        return dp[0];
    }   
};
上一篇 下一篇

猜你喜欢

热点阅读