Explorar o código

feat: palindrome_partition

Zhang Li hai 11 meses
pai
achega
6bdc29d871
Modificáronse 2 ficheiros con 83 adicións e 1 borrados
  1. 2 1
      src/solutions/dp/mod.rs
  2. 81 0
      src/solutions/dp/palindrome_partitioning.rs

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

@@ -13,4 +13,5 @@ mod unique_binary_search_trees;
 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 best_time_to_buy_and_sell_stock3;
+mod palindrome_partitioning;

+ 81 - 0
src/solutions/dp/palindrome_partitioning.rs

@@ -0,0 +1,81 @@
+struct Solution;
+
+
+impl Solution {
+    pub fn partition(s: String) -> Vec<Vec<String>> {
+        let mut res = vec![];
+        let valid = Solution::valid_palindrome(&s[..]);
+        let mut cur = vec![];
+        Solution::helper(&s[..], &valid, 0, s.len(), &mut cur, &mut res);
+
+        res
+
+    }
+
+    fn helper(s: &str, valid: &Vec<Vec<bool>>, begin: usize, n: usize, cur: &mut Vec<String>, res: &mut Vec<Vec<String>>) {
+        if begin == n {
+            res.push(cur.clone());
+            return
+        }
+
+        for end in begin..n {
+            if !valid[begin][end] {
+                continue;
+            } else {
+                cur.push(s[begin..(end+1)].to_string());
+                Solution::helper(s, valid, end+1, n, cur, res);
+                cur.pop();
+            }
+        }
+
+    }
+
+    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_partition() {
+        let s = String::from("aab");
+
+        let res = Solution::partition(s);
+        assert_eq!(res, vec![vec!["a","a","b"], vec!["aa","b"]]);
+    }
+
+    #[test]
+    fn test_partition1() {
+        let s = String::from("a");
+
+        let res = Solution::partition(s);
+        assert_eq!(res, vec![vec!["a"]]);
+    }
+}