Leetcode 409. Longest Palindrome 构造最长回文串 解题报告

来源:互联网 发布:神枪手交易软件 编辑:程序博客网 时间:2024/05/17 08:07

1 解题思想

这道题并不是求字符串里最长的回文串,而是说用这些字符可以构成多长的回文串。

所谓的回文串,就是要左右对称,所以除了中心的那个位置的字符可以出现奇数次以外,都要出现偶数次。

如此,方式就很简单了:
1、统计所有字母的出现频率(分大小写)
2、统计只出现奇数次数字母的个数
3、如果2中结果不为0,字符串的长度减去2中的字母个数+1

其中3的意思是,保留出现次数最多的那个奇数字母,剩下的需要全部减1变成偶数去构造

类似的题目:
Leetcode #5 Longest Palindromic Substring 最长回文串 解题小节

Leetcode #9 Palindrome Number 回文数 解题小节

2 原题

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.

3 AC解

public class Solution {    //统计所有的字母,最终等于所有的出现为偶数的次数+所有奇数的次数-(奇数的个数 - 1),如果没有奇数则不减    public int longestPalindrome(String s) {        char chars[] = s.toCharArray();        int lowerCount[] = new int[26];        int upperCount[] = new int[26];        int odds = 0;        int n = s.length();        for(int i=0;i<n;i++){            if(chars[i] < 'a') upperCount[chars[i]-'A'] ++;            else lowerCount[chars[i] - 'a']++;        }        for(int i=0;i<26;i++){            if(lowerCount[i]%2==1) odds++;            if(upperCount[i]%2==1) odds++;        }        if(odds == 0)            return n;        else return n - odds + 1;    }}
1 0
原创粉丝点击