409. Longest Palindrome+askii码总共128位

来源:互联网 发布:网络市场发展趋势 编辑:程序博客网 时间:2024/06/04 00:54

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.
public class Solution {    public int longestPalindrome(String s) {        int[] table=new int[52];        int count=0,flag=0;                for(Character i:s.toCharArray()){            if(i<='z'&&i>='a')table[i-'a'+26]++;//这里需要注意,因为在askii表总大写字母和小写字母并不是直接相连的,中间有6个其他字符            else table[i-'A']++;        }        for(int i=0;i<table.length;i++){            if(table[i]%2==0){                count+=table[i];                            }            else if(table[i]>2){                count+=table[i]-1;                flag++;            }            else flag++;        }        if(flag>0)count++;        return count;    }}

大神的求解过程省略flag计算单个字母个数,使用计算出偶数个数与总数量比较,若总个数大则存在单个字母,若相等则不存在单个字母

public int longestPalindrome(String s) {    int[] count = new int[128];//对照askii码总共128位    for (char a : s.toCharArray()) {      count[a]++;    }    int max = 0;    for (int i : count) {      if (i > 1) {        max += i / 2;      }    }    return max * 2 + 1 > s.length() ? max * 2 : max * 2 + 1;  }





原创粉丝点击