Leetcode409. Longest Palindrome
Posted wuezs
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode409. Longest Palindrome相关的知识,希望对你有一定的参考价值。
题目链接:https://leetcode.com/contest/7/problems/longest-palindrome/
题目:
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.
思路:
easy 统计每种字符出现次数,分奇偶情况讨论。
算法:
public int longestPalindrome(String s)
if (s.length() == 0)
return 0;
int lm[] = new int[26];
int um[] = new int[26];
for (char c : s.toCharArray())
if (Character.isLowerCase(c))
lm[c - 'a']++;
else
um[c - 'A']++;
int count = 0;
boolean flag = false;// 是否有单个字符
for (int num : lm)
if (num % 2 == 0)
count += num;
else
if (flag)
count += num - 1;
else
count += num;
flag = true;
for (int num : um)
if (num % 2 == 0)
count += num;
else
if (flag)
count += num - 1;
else
count += num;
flag = true;
return count;
以上是关于Leetcode409. Longest Palindrome的主要内容,如果未能解决你的问题,请参考以下文章
[leetcode-409-Longest Palindrome]
LeetCode——409. Longest Palindrome
Leetcode_409_Longest Palindrome
[LeetCode&Python] Problem 409. Longest Palindrome