Leetcode. 回文文字列の分割と最小分割数
4014 ワード
Q 1:回文文字列の分割
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"]
]
アルゴリズム遡及法
For example, given s = "aab",
Return
[
["aa","b"],
["a","a","b"]
]
文字列「abc」を例に挙げる.
インプリメンテーション
class Solution {
public:
vector> partition(string s) {
std::vector<:vector> > results;
std::vector<:string> res;
dfs(s, 0, res, results);
return results;
}
private:
void dfs(std::string& s, int startIndex,
std::vector<:string> res,
std::vector<:vector> >& 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();
}
}
}
};
Q 2回文文字列の最小分割数
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:
For example, given s = "aab",
Return 1 since the palindrome partitioning
["aa","b"] could be produced using 1 cut.
インプリメンテーション
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];
}
};