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
|
use super::Solution;
impl Solution {
pub fn longest_palindrome(s: String) -> String {
let bytes = s.as_bytes();
let len = bytes.len();
return match len {
0 => "".to_string(),
1 => s,
_ => {
let mut max_length = 1;
let mut result = &bytes[0..1];
for i in 1..len {
let mut left_iter = bytes[..i].iter().enumerate().rev();
let mut odd_right_iter = bytes.iter().enumerate().skip(i + 1);
let mut even_right_iter = bytes.iter().enumerate().skip(i);
let mut count_odd = true;
let mut count_even = true;
while count_odd || count_even {
match left_iter.next() {
Some((index_left, left)) => {
if count_odd {
match odd_right_iter.next() {
Some((index_right, right)) => {
if right == left {
let length = index_right - index_left + 1;
if length > max_length {
max_length = length;
result = &bytes[index_left..index_right + 1];
}
} else {
count_odd = false;
}
}
None => count_odd = false,
}
}
if count_even {
match even_right_iter.next() {
Some((index_right, right)) => {
if right == left {
let length = index_right - index_left + 1;
if length > max_length {
max_length = length;
result = &bytes[index_left..index_right + 1];
}
} else {
count_even = false;
}
}
None => count_even = false,
}
}
}
None => break,
}
}
}
String::from_utf8(Vec::from(result)).unwrap()
}
};
}
}
#[cfg(test)]
mod tests {
use super::Solution;
#[test]
fn test() {
assert_eq!(
Solution::longest_palindrome("bb".to_string()),
"bb".to_string()
);
assert_eq!(
Solution::longest_palindrome("abb".to_string()),
"bb".to_string()
);
assert_eq!(
Solution::longest_palindrome("abbc".to_string()),
"bb".to_string()
);
assert_eq!(
Solution::longest_palindrome("abccb".to_string()),
"bccb".to_string()
);
assert_eq!(
Solution::longest_palindrome("abcdcbd".to_string()),
"bcdcb".to_string()
);
assert_eq!(
Solution::longest_palindrome("aaaabaaa".to_string()),
"aaabaaa".to_string()
);
}
}
|