-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpalindrome_partitioning.rs
43 lines (38 loc) · 1.09 KB
/
palindrome_partitioning.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#![allow(dead_code)]
pub fn partition(s: String) -> Vec<Vec<String>> {
let mut res = Vec::new();
let s: Vec<char> = s.chars().collect();
fn is_palindrome(s: &[char]) -> bool {
let rev: Vec<char> = s.iter().rev().cloned().collect();
s == &rev[..]
}
fn backtracking(start: usize, path: &mut Vec<String>, s: &[char], res: &mut Vec<Vec<String>>) {
if start == s.len() {
res.push(path.clone());
return;
}
for end in start + 1..=s.len() {
if is_palindrome(&s[start..end]) {
path.push(s[start..end].iter().collect());
backtracking(end, path, s, res);
path.pop();
}
}
}
backtracking(0, &mut Vec::new(), &s, &mut res);
res
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_partition() {
assert_eq!(
partition("aab".to_string()),
vec![
vec!["a".to_string(), "a".to_string(), "b".to_string()],
vec!["aa".to_string(), "b".to_string()],
]
);
}
}