返回信息流update: 理解错题意了,比如9个a,我可以只取8个,
----------------
Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters.
This is case sensitive, for example "Aa" is not considered a palindrome here.
Note:
Assume the length of given string will not exceed 1,010.
Example:
Input:
"abccccdd"
Output:
7
Explanation:
One longest palindrome that can be built is "dccaccd", whose length is 7.
下面是解法,绝大多数的case过了,
”civilwartestingwhetherthatnaptionoranynartionsoconceivedandsodedicatedcanlongendureWeareqmetonagreatbattlefiemldoftzhatwarWehavecometodedicpateaportionofthatfieldasafinalrestingplaceforthosewhoheregavetheirlivesthatthatnationmightliveItisaltogetherfangandproperthatweshoulddothisButinalargersensewecannotdedicatewecannotconsecratewecannothallowthisgroundThebravelmenlivinganddeadwhostruggledherehaveconsecrateditfaraboveourpoorponwertoaddordetractTgheworldadswfilllittlenotlenorlongrememberwhatwesayherebutitcanneverforgetwhattheydidhereItisforusthelivingrathertobededicatedheretotheulnfinishedworkwhichtheywhofoughtherehavethusfarsonoblyadvancedItisratherforustobeherededicatedtothegreattdafskremainingbeforeusthatfromthesehonoreddeadwetakeincreaseddevotiontothatcauseforwhichtheygavethelastpfullmeasureofdevotionthatweherehighlyresolvethatthesedeadshallnothavediedinvainthatthisnationunsderGodshallhaveanewbirthoffreedomandthatgovernmentofthepeoplebythepeopleforthepeopleshallnotperishfromtheearth“
这个没过,应该返回983,我返回655了
public int longestPalindrome1(String s) {
Map<Character, Integer> map = new HashMap<>();
for (Character ch : s.toCharArray()) map.put(ch, map.getOrDefault(ch, 0) + 1);
int odd = -1;
int ans = 0;
for (Character ch : map.keySet()) {
if (map.get(ch) % 2 == 0) {
ans += map.get(ch);
} else if (map.get(ch) > odd) {
odd = map.get(ch);
}
}
return odd > -1 ? ans + odd : ans;
}
这是一条镜像帖。来源:北邮人论坛 / acm-icpc / #98299同步于 2019/9/3
该镜像源已超过 30 天没有更新,可能在源站已被删除。
ACM_ICPC机器人发帖
我这题的解法为啥是错的?
byrunner
2019/9/3镜像同步5 回复
订阅后,新回复会通过你的通知中心匿名送达。
5 条回复
这个解法就正确。我看不出区别
public int longestPalindrome(String s) {
Set<Character> set = new HashSet<>();
int ans = 0;
for (Character ch : s.toCharArray()) {
if (set.contains(ch)) {
ans++;
set.remove(ch);
} else {
set.add(ch);
}
}
return set.isEmpty() ? ans * 2 : ans * 2 + 1;
}