comments | difficulty | edit_url | tags | |||
---|---|---|---|---|---|---|
true |
简单 |
|
给定一个包含大写字母和小写字母的字符串 s
,返回 通过这些字母构造成的 最长的 回文串 的长度。
在构造过程中,请注意 区分大小写 。比如 "Aa"
不能当做一个回文字符串。
示例 1:
输入:s = "abccccdd" 输出:7 解释: 我们可以构造的最长的回文串是"dccaccd", 它的长度是 7。
示例 2:
输入:s = "a" 输出:1 解释:可以构造的最长回文串是"a",它的长度是 1。
提示:
1 <= s.length <= 2000
s
只由小写 和/或 大写英文字母组成
一个合法的回文字符串,最多存在一个出现奇数次数的字符,其余字符出现次数均为偶数。
因此,我们可以先遍历字符串
然后,我们遍历
最后,如果答案小于字符串
时间复杂度
class Solution:
def longestPalindrome(self, s: str) -> int:
cnt = Counter(s)
ans = sum(v // 2 * 2 for v in cnt.values())
ans += int(ans < len(s))
return ans
class Solution {
public int longestPalindrome(String s) {
int[] cnt = new int[128];
int n = s.length();
for (int i = 0; i < n; ++i) {
++cnt[s.charAt(i)];
}
int ans = 0;
for (int v : cnt) {
ans += v / 2 * 2;
}
ans += ans < n ? 1 : 0;
return ans;
}
}
class Solution {
public:
int longestPalindrome(string s) {
int cnt[128]{};
for (char c : s) {
++cnt[c];
}
int ans = 0;
for (int v : cnt) {
ans += v / 2 * 2;
}
ans += ans < s.size();
return ans;
}
};
func longestPalindrome(s string) (ans int) {
cnt := [128]int{}
for _, c := range s {
cnt[c]++
}
for _, v := range cnt {
ans += v / 2 * 2
}
if ans < len(s) {
ans++
}
return
}
function longestPalindrome(s: string): number {
const cnt: Record<string, number> = {};
for (const c of s) {
cnt[c] = (cnt[c] || 0) + 1;
}
let ans = Object.values(cnt).reduce((acc, v) => acc + Math.floor(v / 2) * 2, 0);
ans += ans < s.length ? 1 : 0;
return ans;
}
use std::collections::HashMap;
impl Solution {
pub fn longest_palindrome(s: String) -> i32 {
let mut cnt = HashMap::new();
for ch in s.chars() {
*cnt.entry(ch).or_insert(0) += 1;
}
let mut ans = 0;
for &v in cnt.values() {
ans += (v / 2) * 2;
}
if ans < (s.len() as i32) {
ans += 1;
}
ans
}
}