美文网首页LeetCode By Go
[LeetCode By Go 51]409. Longest

[LeetCode By Go 51]409. Longest

作者: miltonsun | 来源:发表于2017-08-22 18:46 被阅读4次

    题目

    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

        本文链接:https://www.haomeiwen.com/subject/zsoldxtx.html