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.看错题了,以为是字符串里的最长回文串长度,没想到是字符串里出现的字母能组成的最长回文串的长度……嗯……直接计算每个字母的出现次数,双数就凑一对,单数就能成双的成双,不能成双的留一个下来就好。很简单,只是这题字符串可能有大小写字母,于是就用了个长度128的数组,直接存对应的char就行。
- class Solution {
- public int longestPalindrome(String s) {
- int[] count = new int[128];
- for (char c : s.toCharArray()) {
- count[c]++;
- }
-
- int result = 0;
- boolean hasOdd = false;
- for (int i : count) {
- if (i % 2 == 0) {
- result += i;
- } else {
- result += (i - 1);
- hasOdd = true;
- }
- }
-
- return hasOdd ? result + 1 : result;
- }
- }
看了大家的解法还有人用hashset,如果set里有就remove掉凑一对,最后看看set里还剩没剩,有剩就再+1就行了。代码不写了,贴别人的:Loading...