Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

409. Longest Palindrome #74

Open
Tcdian opened this issue Mar 19, 2020 · 1 comment
Open

409. Longest Palindrome #74

Tcdian opened this issue Mar 19, 2020 · 1 comment

Comments

@Tcdian
Copy link
Owner

Tcdian commented Mar 19, 2020

409. Longest Palindrome

给定一个包含大写字母和小写字母的字符串,找到通过这些字母构造成的最长的回文串。

在构造过程中,请注意区分大小写。比如 "Aa" 不能当做一个回文字符串。

Example

Input:
"abccccdd"

Output:
7

Explanation:
One longest palindrome that can be built is "dccaccd", whose length is 7.

Note

  • Assume the length of given string will not exceed 1,010.
@Tcdian
Copy link
Owner Author

Tcdian commented Mar 19, 2020

Solution

  • JavaScript Solution
/**
 * @param {string} s
 * @return {number}
 */
var longestPalindrome = function(s) {
    const cache = new Map();
    let result = 0;
    let hasSingleLetter = false;
    for (let i = 0; i < s.length; i++) {
        cache.set(s[i], (cache.get(s[i]) || 0) + 1);
    }
    cache.forEach((letter) => {
        result += (letter >> 1) * 2;
        if (letter % 2 === 1) {
            hasSingleLetter = true;
        }
    });
    return result + (hasSingleLetter ? 1 : 0);
};
  • TypeScript Solution
function longestPalindrome(s: string): number {
    const cache: Map<string, number> = new Map();
    let result = 0;
    let hasSingleLetter = false;
    for (let i = 0; i < s.length; i++) {
        cache.set(s[i], (cache.get(s[i]) || 0) + 1);
    }
    cache.forEach((letter) => {
        result += (letter >> 1) * 2;
        if (letter % 2 === 1) {
            hasSingleLetter = true;
        }
    });
    return result + (hasSingleLetter ? 1 : 0);
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant