-
Notifications
You must be signed in to change notification settings - Fork 4
/
main.rs
61 lines (52 loc) · 1.4 KB
/
main.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
fn main() {
println!("Hello, world!");
let mut bytes = "bors".bytes();
assert_eq!(Some(b'b'), bytes.next());
assert_eq!(Some(b'o'), bytes.next());
assert_eq!(Some(b'r'), bytes.next());
assert_eq!(Some(b's'), bytes.next());
assert_eq!(None, bytes.next());
}
pub struct Solution {}
impl Solution {
pub fn longest_palindrome(s: String) -> String {
let vec : Vec<u8> = s.bytes().collect();
let len = vec.len();
if len <= 1 {
return s;
}
let mut start = 0;
let mut end = 0;
for s in 0..len {
for e in s+1..len {
if Solution::is_palindromic(&vec, s, e) && e - s > end - start {
end = e;
start = s;
}
}
}
s[start..end+1].into()
}
fn is_palindromic(s:&[u8], start:usize, end:usize) -> bool {
let mut end = end;
let mut m_start = start;
while m_start < end {
if s[m_start] != s[end] {
return false;
} else {
m_start += 1;
end -= 1;
}
}
true
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn basic() {
assert_eq!(Solution::longest_palindrome(String::from("babad")), "bab");
assert_eq!(Solution::longest_palindrome(String::from("cbbd")), "bb");
}
}