We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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
给定一个包含大写字母和小写字母的字符串,找到通过这些字母构造成的最长的回文串。
在构造过程中,请注意区分大小写。比如 "Aa" 不能当做一个回文字符串。
假设字符串的长度不会超过 1010。
输入: "abccccdd" 输出: 7 解释: 我们可以构造的最长的回文串是"dccaccd", 它的长度是 7。
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/longest-palindrome/
遍历字符串,得到每个字符的数量,存在一个map中,然后遍历map,如果value是偶数,就说明可以构成回文,如果是奇数的话,value-1也可以构成回文,最后如果长度和字符串的长度不一致,就说明还有值,作为中间值即可
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 }
The text was updated successfully, but these errors were encountered:
No branches or pull requests
给定一个包含大写字母和小写字母的字符串,找到通过这些字母构造成的最长的回文串。
在构造过程中,请注意区分大小写。比如 "Aa" 不能当做一个回文字符串。
注意:
假设字符串的长度不会超过 1010。
示例 1:
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-palindrome/
解答
遍历字符串,得到每个字符的数量,存在一个map中,然后遍历map,如果value是偶数,就说明可以构成回文,如果是奇数的话,
value-1
也可以构成回文,最后如果长度和字符串的长度不一致,就说明还有值,作为中间值即可The text was updated successfully, but these errors were encountered: