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