Skip to content

Commit e19b877

Browse files
committed
add: Longest Palindrome
1 parent 86e708a commit e19b877

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

β€Ž0409-longest-palindrome.rs

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
struct Solution;
2+
3+
impl Solution {
4+
pub fn longest_palindrome(s: String) -> i32 {
5+
let mut counts = [0; 128];
6+
for ch in s.into_bytes() {
7+
counts[ch as usize] += 1;
8+
}
9+
let mut longest_palindrome_length = 0;
10+
for count in counts.iter() {
11+
longest_palindrome_length += (count / 2) * 2;
12+
if longest_palindrome_length % 2 == 0 && count % 2 != 0 {
13+
longest_palindrome_length += 1;
14+
}
15+
}
16+
longest_palindrome_length
17+
}
18+
}
19+
20+
fn main() {
21+
assert_eq!(7, Solution::longest_palindrome("abccccdd".to_string()));
22+
assert_eq!(9, Solution::longest_palindrome("abccccddEE".to_string()));
23+
assert_eq!(1, Solution::longest_palindrome("Aa".to_string()));
24+
assert_eq!(2, Solution::longest_palindrome("bb".to_string()));
25+
assert_eq!(1, Solution::longest_palindrome("zZ".to_string()));
26+
}

0 commit comments

Comments
 (0)