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. 最长回文串 #26

Open
yankewei opened this issue Mar 18, 2020 · 0 comments
Open

409. 最长回文串 #26

yankewei opened this issue Mar 18, 2020 · 0 comments
Labels
哈希表 题目包含哈希表解法 简单 题目难度为简单

Comments

@yankewei
Copy link
Owner

yankewei commented Mar 18, 2020

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

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

注意:

假设字符串的长度不会超过 1010。

示例 1:

输入:
"abccccdd"
输出:
7
解释:
我们可以构造的最长的回文串是"dccaccd", 它的长度是 7。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-palindrome/

解答

遍历字符串,得到每个字符的数量,存在一个map中,然后遍历map,如果value是偶数,就说明可以构成回文,如果是奇数的话,value-1也可以构成回文,最后如果长度和字符串的长度不一致,就说明还有值,作为中间值即可

func longestPalindrome(s string) int {
    ret, l := 0, len(s)
    m := make(map[rune]int)
    for _, v := range s {
        m[v]++
    }
    for _, v := range m {
        if v % 2 == 0 {
            ret+=v
        } else {
            ret+= (v-1)
        }
    }
    if ret == l {
        return ret
    }
    return ret+1
}
func main() {
    longestPalindrome("abccccdd") // 7
}
@yankewei yankewei added 简单 题目难度为简单 哈希表 题目包含哈希表解法 labels Mar 18, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
哈希表 题目包含哈希表解法 简单 题目难度为简单
Projects
None yet
Development

No branches or pull requests

1 participant