Skip to content

Commit ebc0a1e

Browse files
committed
feat: add solution for palindrome partiotioning
1 parent f361d42 commit ebc0a1e

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

src/medium/palindrome_partitioning.rs

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

0 commit comments

Comments
 (0)