Skip to content

Commit ea3a79c

Browse files
committed
'Palindrome Partitioning' soln
1 parent 2eecd57 commit ea3a79c

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed

leetcode/palindrome_partitioning.rs

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
///
2+
/// Problem: Palindrome Partitioning
3+
///
4+
/// Given a string s, partition s such that every substring of the partition is a palindrome.
5+
/// Return all possible palindrome partitioning of s.
6+
///
7+
/// Example 1:
8+
/// Input: s = "aab"
9+
/// Output: [["a","a","b"],["aa","b"]]
10+
///
11+
/// Example 2:
12+
/// Input: s = "a"
13+
/// Output: [["a"]]
14+
///
15+
/// Constraints:
16+
/// 1 <= s.length <= 16
17+
/// s contains only lowercase English letters.
18+
///
19+
20+
// # Solution
21+
// Time complexity: O(N * 2^N) where N is the length of the string
22+
// Space complexity: O(N^2)
23+
24+
25+
impl Solution {
26+
pub fn partition(s: String) -> Vec<Vec<String>> {
27+
let mut result = Vec::new();
28+
let mut current_partition = Vec::new();
29+
let s_chars: Vec<char> = s.chars().collect();
30+
31+
Self::backtrack(&s_chars, 0, &mut current_partition, &mut result);
32+
33+
result
34+
}
35+
36+
fn backtrack(s: &[char], start: usize, current: &mut Vec<String>, result: &mut Vec<Vec<String>>) {
37+
if start >= s.len() {
38+
result.push(current.clone());
39+
return;
40+
}
41+
42+
for end in start..s.len() {
43+
if Self::is_palindrome(s, start, end) {
44+
let substring: String = s[start..=end].iter().collect();
45+
current.push(substring);
46+
47+
Self::backtrack(s, end + 1, current, result);
48+
49+
current.pop();
50+
}
51+
}
52+
}
53+
54+
fn is_palindrome(s: &[char], start: usize, end: usize) -> bool {
55+
let mut i = start;
56+
let mut j = end;
57+
58+
while i < j {
59+
if s[i] != s[j] {
60+
return false;
61+
}
62+
i += 1;
63+
j -= 1;
64+
}
65+
66+
true
67+
}
68+
}

0 commit comments

Comments
 (0)