Skip to content

Commit e079576

Browse files
committed
create 2002 in rust
1 parent c3d5f61 commit e079576

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
impl Solution {
2+
pub fn max_product(s: String) -> i32 {
3+
let s: Vec<char> = s.chars().collect();
4+
let mut s1 = vec![];
5+
let mut s2 = vec![];
6+
let mut res = 0;
7+
8+
Solution::dfs(&s, &mut s1, &mut s2, &mut res, 0);
9+
10+
res
11+
}
12+
13+
fn dfs(s: &[char], s1: &mut Vec<char>, s2: &mut Vec<char>, res: &mut i32, index: usize) {
14+
// Base case
15+
if index == s.len() {
16+
if Solution::is_palindrome(s1) && Solution::is_palindrome(s2) {
17+
let new_max = s1.len() * s2.len();
18+
*res = std::cmp::max(*res, new_max as i32);
19+
}
20+
return;
21+
}
22+
23+
// Option 0: Not in S1 nor S2
24+
Solution::dfs(s, s1, s2, res, index + 1);
25+
26+
// Option 1: in S1
27+
s1.push(s[index]);
28+
Solution::dfs(s, s1, s2, res, index + 1);
29+
s1.pop();
30+
31+
// Option 2: in S2
32+
s2.push(s[index]);
33+
Solution::dfs(s, s1, s2, res, index + 1);
34+
s2.pop();
35+
}
36+
37+
fn is_palindrome(s: &[char]) -> bool {
38+
if s.len() <= 1 {
39+
return true;
40+
}
41+
42+
let mut l = 0;
43+
let mut r = s.len() - 1;
44+
45+
while l < r {
46+
if s[l] != s[r] {
47+
return false;
48+
}
49+
l += 1;
50+
r -= 1;
51+
}
52+
53+
true
54+
}
55+
}

0 commit comments

Comments
 (0)