Algorithm之路四百零九:Longest Palindrome

题目:

给出一个字符串,输出能由字符串中的字符构建的回文序列的长度的最大值,区分大小写。

举例:

"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)了。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值