Palindrome Partitioning II
Q:
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.
A:
跟I类似,还是先保存每个子字符串是否为回文。同样A[i]与A[0].....A[i - 1]息息相关,还是比较easy的
class Solution { public: int minCut(string s) { // Start typing your C/C++ solution below // DO NOT write int main() function Prepare(s); if (s.empty()) return 0; int len = s.length(); min_cuts_.resize(len, 0); for (int i = 1; i < len; ++i) { if (is_pal_[0][i]) { min_cuts_[i] = 0; continue; } min_cuts_[i] = i; for (int j = 0; j < i; ++j) { if (!is_pal_[j + 1][i]) continue; min_cuts_[i] = min(min_cuts_[j] + 1, min_cuts_[i]); } } return min_cuts_.back(); } private: void Prepare(const string& s) { min_cuts_.clear(); is_pal_.clear(); if (s.empty()) return; int len = s.length(); is_pal_.resize(len, vector<bool>()); for (int i = 0; i < len; ++i) { is_pal_[i].resize(len, false); } for (int i = 0; i < len; ++i) is_pal_[i][i] = true; for (int i = len - 2; i >= 0; --i) { is_pal_[i][i + 1] = (s[i] == s[i + 1]); for (int j = i + 2; j < len; ++j) { is_pal_[i][j] = (s[i] == s[j] && is_pal_[i + 1][j - 1]); } } } vector<int> min_cuts_; vector<vector<bool> > is_pal_; };
Passion, patience, perseverance, keep it and move on.

浙公网安备 33010602011771号