题目:
给出一个字符串,输出能由字符串中的字符构建的回文序列的长度的最大值,区分大小写。
举例:
"abcccdd" ---> 7,因为可以构成的回文序列为"dccaccd",长度为7。
思路:
遍历整个字符串,将字符串中各个字母的出现次数统计起来,用hash表可以很方便的实现查找和添加。最后将各个字母的出现次数加起来,减去出现次数为奇数的字母个数,在加上1即可,如果没有字母的出现次数为奇数,那么不加1。
之前做过的题目中有一道题是计算最长的回文子串,但是这道题和之前那道题不一样,因为这一次求得不是子串,而是可以由串中的字母构成的回文序列,字母的顺序不做限制,解法很明显,出现次数为偶数的字母肯定可以放到回文串中,出现次数为奇数的字母可以放入n-1个字母到回文串中,n为出现次数为奇数的字母的出现个数。并且最终得到的回文串中只允许有一个字母的出现个数为奇数。根据以上的分析,就可以得出结果。
代码:
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class Longest_Palindrome {
public static int longestPalindrome(String s) {
Map<Character,Integer> map = new HashMap<>();
int length = 0;
int odd = 0;
for(int i = 0;i < s.length();i++)
{
char ch = s.charAt(i);
if(map.containsKey(ch))
map.put(ch, map.get(ch)+1);
else
map.put(ch, 1);
}
Iterator iter = map.entrySet().iterator();
while (iter.hasNext())
{
Map.Entry entry = (Map.Entry) iter.next();
char key = (char)entry.getKey();
int val = (int)entry.getValue();
length += val;
if(val %2 == 1)
odd++;
}
if(odd == 0)
return length - odd;
return length - odd + 1;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(longestPalindrome("civilwartestingwhetherthatnaptionoranynartionsoconceivedandsodedicatedcanlongendureWeareqmetonagreatbattlefiemldoftzhatwarWehavecometodedicpateaportionofthatfieldasafinalrestingplaceforthosewhoheregavetheirlivesthatthatnationmightliveItisaltogetherfangandproperthatweshoulddothisButinalargersensewecannotdedicatewecannotconsecratewecannothallowthisgroundThebravelmenlivinganddeadwhostruggledherehaveconsecrateditfaraboveourpoorponwertoaddordetractTgheworldadswfilllittlenotlenorlongrememberwhatwesayherebutitcanneverforgetwhattheydidhereItisforusthelivingrathertobededicatedheretotheulnfinishedworkwhichtheywhofoughtherehavethusfarsonoblyadvancedItisratherforustobeherededicatedtothegreattdafskremainingbeforeusthatfromthesehonoreddeadwetakeincreaseddevotiontothatcauseforwhichtheygavethelastpfullmeasureofdevotionthatweherehighlyresolvethatthesedeadshallnothavediedinvainthatthisnationunsderGodshallhaveanewbirthoffreedomandthatgovernmentofthepeoplebythepeopleforthepeopleshallnotperishfromtheearth"));
}
}
问题:
看到大神的代码只需要5行,感到真心佩服,不过因为我的层次太低,所以感觉不到代码的美感,因为我读不懂,理解起来很费劲,QAQ。
我提交之前,居然忘记了所有字母出现次数均为偶数的状况,造成了一次WRONG ANSWER,不过没关系,因为,我遇到过不少的WRONG ANSWER,已经被打击习惯了,不过这是一个教训,一定要看的远一些,考虑得多一些。
时间复杂度:
因为需要将整个字符串遍历一遍,所以时间复杂度为O(n),n为字符串的长度。
空间复杂度:
O(min(m,n),n为字符串的长度,m为字符串中出现的字母的种类数,因为需要哈希表的空间,实际上也就是O(m)了。