LeetCode 409. Longest Palindrome 最长回文字串

Question:

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:
7

Explanation:
One longest palindrome that can be built is "dccaccd", whose length is 7.

问题:

已知一个只包括大小写字符的字符串,求用该字符串中的字符可以生成的最长回文字符串长度。

例如 s = "abccccddaa"可生成的最长回文字符串长度为9,如ddccaaaccd,acdcacdca等都正确。

思路:

采用字符hash方法,统计字符串中所有字符数量。

若某个字符个数为偶数,则全部可以用来构成回文串。

若某个字符个数为奇数,则(总个数-1)个可以用来构成回文串,并且设置一个flag变量,存在奇数个某字符的时候,可以选择一个作为中心字符,即回文串长度+1。

class Solution {
    public int longestPalindrome(String s) {
        int [] char_map = new int[128]; //建立字符hash表,存储每个字符的个数
        int flag = 0; //判断string中的每个字符个数是否为奇数,若为奇数,则flag=1;
        int result = 0;
        for(int i = 0; i<s.length();i++)
            char_map[s.charAt(i)]++;
        for(int i = 0; i<char_map.length;i++)
        {
            if(char_map[i]%2==0)//若某个字符个数为偶数,全部可以用来构成回文串,长度直接加入result
                result = result + char_map[i];
            else
            {
                result = result + char_map[i]-1;
                flag = 1; //若某个字符个数为偶数,长度-1可以用来构成回文串,并且flag置1,可以选择某一个作为中心字符
            }
        }
        if(flag==1)
            return result+1;
        else
            return result;
    }
}
博主学习笔记,转载请注明出处,谢谢~
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值