leetcode_rust/problems/p000_0xx/
p000_005.rs1pub fn longest_palindrome(s: String) -> String {
40 by_array_index(&s).to_string()
41}
42
43#[cfg(test)]
44#[test]
45fn test_longest_palindrome() {
46 assert!(longest_palindrome(String::from("abbbabbbac")) == String::from("abbbabbba"));
47}
48
49#[allow(unused_assignments)]
50fn by_array_index(s: &str) -> &str {
51 let b = s.as_bytes();
52 if b.len() == 1 {
53 return s;
54 }
55
56 let mut cur_longest_start_idx = 0;
57 let mut cur_longest_end_idx = 0;
58 let mut ite = 1;
59 let mut cur_start_idx = 0;
60 let mut cur_end_idx = 0;
61 let mut should_repeat = false;
62 while ite <= b.len() - 1 || should_repeat {
63 cur_start_idx = ite - 1;
64 cur_end_idx = ite;
65 if should_repeat {
66 if ite < b.len() - 1 {
67 cur_end_idx = ite + 1;
68 }
69 ite += 1;
70 }
71 should_repeat = !should_repeat;
72 while cur_start_idx > 0 && cur_end_idx < b.len() - 1 && b[cur_end_idx] == b[cur_start_idx] {
73 cur_start_idx -= 1;
74 cur_end_idx += 1;
75 }
76 if b[cur_end_idx] != b[cur_start_idx]
77 && cur_end_idx - cur_start_idx > 2
78 && b[cur_end_idx - 1] == b[cur_start_idx + 1]
79 {
80 cur_end_idx -= 1;
81 cur_start_idx += 1;
82 } else if b[cur_end_idx] != b[cur_start_idx] {
83 continue;
84 }
85 if cur_end_idx - cur_start_idx > cur_longest_end_idx - cur_longest_start_idx {
86 cur_longest_end_idx = cur_end_idx;
87 cur_longest_start_idx = cur_start_idx;
88 }
89 }
90 &s[cur_longest_start_idx..(cur_longest_end_idx + 1)]
91}
92
93#[cfg(test)]
94#[test]
95fn test_by_array_index() {
96 assert!(by_array_index("QQ") == String::from("QQ"));
97 assert!(by_array_index("QAQ") == String::from("QAQ"));
98}