409. Longest Palindrome

忘是亡心i 2022-03-07 14:00 262阅读 0赞

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:

  1. Input:
  2. "abccccdd"
  3. Output:
  4. 7
  5. Explanation:
  6. One longest palindrome that can be built is "dccaccd", whose length is 7.

难度:easy

题目:给定包含大小写字符组成的字符串,找出用这些字符串所能够成的最长回文串。

思路:字符统计

Runtime: 5 ms, faster than 90.61% of Java online submissions for Longest Palindrome.
Memory Usage: 34.7 MB, less than 100.00% of Java online submissions for Longest Palindrome.

  1. class Solution {
  2. public int longestPalindrome(String s) {
  3. int[] table = new int[255];
  4. for (char c: s.toCharArray()) {
  5. table[c]++;
  6. }
  7. int length = 0, odd = 0;
  8. for (int i = 0; i < 255; i++) {
  9. if (table[i] % 2 > 0) {
  10. odd = 1;
  11. }
  12. length += table[i] - table[i] % 2;
  13. }
  14. return length + odd;
  15. }
  16. }

发表评论

表情:
评论列表 (有 0 条评论,262人围观)

还没有评论,来说两句吧...

相关阅读