-
Notifications
You must be signed in to change notification settings - Fork 0
/
longest_palindromic_substring.rs
103 lines (84 loc) · 2.58 KB
/
longest_palindromic_substring.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
/// Given a string `s`, return the longest palindromic substring in s.
pub struct Solution;
impl Solution {
fn worker(letters: &Vec<char>, left: usize, right: usize) -> usize {
let n = letters.len();
let mut result = 0;
let mut left = left;
let mut right = right;
let mut left_letter = letters[left];
let mut right_letter = letters[right];
while left_letter == right_letter {
result = right - left + 1;
if left == 0 || right == n-1 {
break;
} else {
left -= 1;
right += 1;
left_letter = letters[left];
right_letter = letters[right];
}
}
result
}
fn get_palindrome(letters: &Vec<char>, i: usize, len: usize) -> String {
let start = i - (len - 1) / 2;
let end = i + len / 2 + 1;
letters[start..end].iter().collect()
}
pub fn longest_palindrome(s: String) -> String {
let mut result = String::from("");
let mut result_len = 0;
let letters: Vec<char> = s.chars().collect();
let n = letters.len();
for i in 0..n {
let centered = Self::worker(&letters, i, i);
if centered > result_len {
result = Self::get_palindrome(&letters, i, centered);
result_len = result.len();
}
}
for i in 0..n-1 {
let between = Self::worker(&letters, i, i+1);
if between > result_len {
result = Self::get_palindrome(&letters, i, between);
result_len = result.len();
}
}
result
}
}
#[cfg(test)]
mod tests {
use super::Solution;
#[test]
fn example_1() {
let s = "babad".to_string();
let result = Solution::longest_palindrome(s);
assert!(result == "bab" || result == "aba")
}
#[test]
fn example_2() {
let s = "cbbd".to_string();
let result = Solution::longest_palindrome(s);
assert_eq!(result, "bb");
}
#[test]
fn longer() {
let s = "hellohowareyoutodayracecarblueseriously".to_string();
let result = Solution::longest_palindrome(s);
assert_eq!(result, "racecar");
}
#[test]
fn single() {
let s = "a".to_string();
let result = Solution::longest_palindrome(s);
assert_eq!(result, "a");
}
#[test]
fn double() {
let s = "bb".to_string();
let result = Solution::longest_palindrome(s);
assert_eq!(result, "bb");
}
}