[LeetCode By Go 51]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.

解题思路

遍历字符串,将字符和对应出现的次数放进map中
字符每出现两次,则最大回文串长度+2
有一个字符出现是单数,则最大回文串长度再+1

代码

func longestPalindrome(s string) int {
    var length int
    
    len1 := len(s)
    if len1 < 2 {
        return len1
    }
    sRune := []rune(s)
    var charMap map[rune]int
    charMap = make(map[rune]int)

    for _, v := range sRune {
        charMap[v]++
    }

    var middle bool
    for _, v := range charMap {
        if 0 != v % 2 {
            middle = true
        }
        length += v - v%2
    }
    
    if middle {
        length++
    }
    return length
}

你可能感兴趣的:([LeetCode By Go 51]409. Longest Palindrome)