活动地址:CSDN21天学习挑战赛
题目描述
英文版描述
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.
英文版地址
https://leetcode.com/problems/longest-palindrome/
中文版描述
给定一个包含大写字母和小写字母的字符串 s ,返回 通过这些字母构造成的 最长的回文串 。 在构造过程中,请注意 区分大小写 。比如 "Aa" 不能当做一个回文字符串。
示例 1:
输入:s = "abccccdd"
输出:7
解释: 我们可以构造的最长的回文串是"dccaccd", 它的长度是 7。
示例 2:
输入:s = "a"
输入:1
示例 3:
输入:s = "bb"
输入: 2
提示:
-
1 <= s.length <= 2000
-
s 只能由小写和/或大写英文字母组成
中文版地址
https://leetcode.cn/problems/longest-palindrome/
解题思路
回文串只有中间的字符可以是单个的,其余的必须是双数,所以我们先遍历输入的字符串,将它存放在Map<字符,数目>中(由于区分大小写,不然可以借鉴之前的默认27个字母的数组减少空间复杂度)
解题方法
俺这版
class Solution {
public int longestPalindrome(String s) {
Map<Character, Integer> map = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
if (map.containsKey(s.charAt(i))) {
map.put(s.charAt(i), map.get(s.charAt(i))+1);
} else {
map.put(s.charAt(i), 1);
}
}
int count = 0;
int countDouble = 0;
for (Map.Entry entry : map.entrySet()) {
Integer value = (Integer) entry.getValue();
if (value > 0) {
if (value % 2 == 0) {
countDouble += (value / 2);
} else {
count = 1;
countDouble += (value / 2);
}
}
}
return count + countDouble * 2;
}
}
复杂度分析
-
时间复杂度
遍历字符串(设字符串长度为n) n + 遍历哈希表n = 2n,O(2n)=O(n)
-
空间复杂度
由于 ASCII 字符数量为128(区分大小写) ,哈希表最多使用128 + 计数 2 = 130,O(130)=O(1)
官方版
class Solution {
public int longestPalindrome(String s) {
int[] count = new int[128];
int length = s.length();
for (int i = 0; i < length; ++i) {
char c = s.charAt(i);
count[c]++;
}
int ans = 0;
for (int v: count) {
ans += v / 2 * 2;
if (v % 2 == 1 && ans % 2 == 0) {
ans++;
}
}
return ans;
}
}