|
@@ -0,0 +1,73 @@
|
|
|
+struct Solution;
|
|
|
+
|
|
|
+impl Solution {
|
|
|
+ pub fn min_cut(s: String) -> i32 {
|
|
|
+
|
|
|
+ let valid = Solution::valid_palindrome(&s[..]);
|
|
|
+ let s = s.chars().collect::<Vec<char>>();
|
|
|
+
|
|
|
+ let n = s.len();
|
|
|
+ let mut dp = vec![n as i32;n];
|
|
|
+ dp[0] = 0;
|
|
|
+
|
|
|
+ for i in 1..n {
|
|
|
+ for k in 0..=i {
|
|
|
+ if k == 0 {
|
|
|
+ if valid[k][i] {
|
|
|
+ dp[i] = dp[i].min(0);
|
|
|
+ }
|
|
|
+
|
|
|
+ } else {
|
|
|
+ if valid[k][i] {
|
|
|
+ dp[i] = dp[i].min(dp[k-1] + 1);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ dp[n-1]
|
|
|
+
|
|
|
+ }
|
|
|
+
|
|
|
+
|
|
|
+ fn valid_palindrome(s: &str) -> Vec<Vec<bool>> {
|
|
|
+ let s = s.chars().collect::<Vec<char>>();
|
|
|
+ let n = s.len();
|
|
|
+ let mut res = vec![vec![false; n]; n];
|
|
|
+
|
|
|
+ for i in 0..n {
|
|
|
+ res[i][i] = true;
|
|
|
+ }
|
|
|
+ for l in 2..=n {
|
|
|
+ for i in 0..(n-l+1) {
|
|
|
+ let j = i + l - 1;
|
|
|
+ if l == 2 {
|
|
|
+ if s[i] == s[j] {
|
|
|
+ res[i][j] = true;
|
|
|
+ }
|
|
|
+
|
|
|
+ } else {
|
|
|
+ res[i][j] = res[i+1][j-1] && s[i] == s[j]
|
|
|
+ }
|
|
|
+
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+ res
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+#[cfg(test)]
|
|
|
+mod tests {
|
|
|
+ use super::*;
|
|
|
+
|
|
|
+ #[test]
|
|
|
+ fn test_min_cut() {
|
|
|
+ let s = String::from("aab");
|
|
|
+ let res = Solution::min_cut(s);
|
|
|
+ assert_eq!(res, 1);
|
|
|
+
|
|
|
+ }
|
|
|
+}
|