409. Longest Palindrome

来源:互联网 发布:java else 必须 编辑:程序博客网 时间:2024/05/16 17:26

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.


只求长度不求具体的串,每有2个相同的字母就可以放在头尾两边,还有“落单”的字母可以拿一个放在中间作为对称轴。

public class Solution {    public int longestPalindrome(String s){int len=s.length();int[] arr=new int[128];for(int i=0;i<len;i++)arr[s.charAt(i)]++;int sum=0;boolean hasSingle=false;for(int i=0;i<128;i++){sum+=arr[i]/2;arr[i]%=2;if(arr[i]==1)hasSingle=true;}return sum*2+(hasSingle?1:0);}}


0 0
原创粉丝点击