Przeglądaj źródła

feat: palindrome_partition2

Zhang Li 11 miesięcy temu
rodzic
commit
d124b990ca

+ 2 - 1
src/solutions/dp/mod.rs

@@ -14,4 +14,5 @@ mod distinct_subsequences;
 mod best_time_to_buy_and_sell_stock;
 mod best_time_to_buy_and_sell_stock2;
 mod best_time_to_buy_and_sell_stock3;
-mod palindrome_partitioning;
+mod palindrome_partitioning;
+mod palindrome_partitioning2;

+ 73 - 0
src/solutions/dp/palindrome_partitioning2.rs

@@ -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);
+
+    }
+}