[LeetCode] 409. Longest Palindrome

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.

最长回文串。题意是给一堆字母,有大小写,请找到通过这些字母构造成的最长的回文串,返回的是回文串的长度。

思路是遍历input,并用一个hashmap存字母的出现次数。如果某字母存在于hashmap则map[char]--,res += 2;如果某字母不存在于hashmap则把它加入hashmap,map[char] = 1。最后遍历hashmap,看是否还存在map[char]不为零的情况,若还有不为零的字母则最长的回文串长度是res + 1(会形成类似aba这样的回文);否则则是res(会形成类似abba这样的回文)。

时间O(n)

空间O(n)

Java实现

 1 class Solution {
 2     public int longestPalindrome(String s) {
 3         // corner case
 4         if (s == null || s.length() == 0) {
 5             return 0;
 6         }
 7 
 8         // normal case
 9         int res = 0;
10         char[] count = new char[256];
11         for (char c : s.toCharArray()) {
12             if (count[c] > 0) {
13                 count[c]--;
14                 res += 2;
15             } else {
16                 count[c]++;
17             }
18         }
19 
20         for (int i = 0; i < 256; i++) {
21             if (count[i] != 0) {
22                 res++;
23                 break;
24             }
25         }
26         return res;
27     }
28 }

JavaScript实现

 1 /**
 2  * @param {string} s
 3  * @return {number}
 4  */
 5 var longestPalindrome = function (s) {
 6     // corner case
 7     if (s == null || s.length == 0) {
 8         return 0;
 9     }
10 
11     // normal case
12     let map = {};
13     let res = 0;
14     let flag = false;
15     for (let c of s) {
16         if (map[c] !== undefined) {
17             map[c] = undefined;
18             res++;
19         } else {
20             map[c] = 1;
21         }
22     }
23 
24     for (key in map) {
25         if (map[key] !== undefined) {
26             flag = true;
27         }
28     }
29     if (flag) return res * 2 + 1;
30     return res * 2;
31 };

LeetCode 题目总结

原文地址:https://www.cnblogs.com/cnoodle/p/12521832.html