LeetCode 409. Longest Palindrome #86
quinnwencn
started this conversation in
General
Replies: 1 comment 1 reply
-
AnalisysSolution written in Cpp#pragma once
#include <string>
#include <array>
class Solution {
public:
int longestPalindrome(std::string s) {
std::array<uint16_t, 100> chars {0};
for (auto c: s) {
chars[c - 'A']++;
}
uint16_t count {0};
bool onceFlag {true};
for (auto i: chars) {
if ((i > 1) && (i % 2 == 0)) {
count += i;
} else {
count += i > 0 ? i-1 : 0;
}
if (onceFlag && i % 2 == 1) {
count++;
onceFlag = false;
}
}
return count;
}
};Solution written in Rustimpl Solution {
pub fn longest_palindrome(s: String) -> i32 {
let mut chars = [0; 100];
s.chars().for_each(|c| { chars[c as usize - 'A' as usize] += 1; });
let mut count = 0;
let mut once = true;
for i in chars {
if i % 2 == 0 {
count += i;
} else if i % 2 == 1 {
count += i - 1;
if once {
count += 1;
once = false;
}
}
}
count
}
} |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Description
Given a string s which consists of lowercase or uppercase letters, return the length of the longest palindrome that can be built with those letters.
Letters are case sensitive, for example, "Aa" is not considered a palindrome here.
Example 1:
Input: s = "abccccdd"
Output: 7
Explanation: One longest palindrome that can be built is "dccaccd", whose length is 7.
Example 2:
Input: s = "a"
Output: 1
Explanation: The longest palindrome that can be built is "a", whose length is 1.
Constraints:
1 <= s.length <= 2000
s consists of lowercase and/or uppercase English letters only.
Beta Was this translation helpful? Give feedback.
All reactions