本文主要是介绍[LeetCode] 409. Longest Palindrome,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题:https://leetcode.com/problems/longest-palindrome/description/
题目
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:
7Explanation:
One longest palindrome that can be built is "dccaccd", whose length is 7.
题目大意
计算一组字符集合可以组成的回文字符串的最大长度
思路
1.计算 字符串中,每个字符的 对数。在回文字符中,成对的数放入。
2.若由字符对数 组成的 回文字符 长度小于 原字符串,则 可以有个单独字符 作为 回文串的中心。
class Solution {public int longestPalindrome(String s) {Map<Character,Integer> map = new HashMap();for(char c : s.toCharArray())map.put(c,map.getOrDefault(c,0)+1);int res = 0;int center = 0;for(char c : map.keySet()){res += map.get(c)/2;}res = res<<1;if(res<s.length())res++;return res;}
}
这篇关于[LeetCode] 409. Longest Palindrome的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!