国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計(jì) > 正文

LeetCode -- Longest Palindrome

2019-11-08 02:11:35
字體:
供稿:網(wǎng)友
題目描述: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.給定一個(gè)字符串,利用字符串中的字符組成回文,返回最大回文長度。一開始以為本題是判斷字符串存在的最大回文長度,準(zhǔn)備使用分治。后來仔細(xì)看發(fā)現(xiàn)不是,直接使用哈希統(tǒng)計(jì)每個(gè)字符出現(xiàn)次數(shù)即可:如果為偶數(shù):直接累加。如果是奇數(shù),判斷-1后是否為偶數(shù),如果為偶數(shù),累加這個(gè)偶數(shù)。標(biāo)記是否出現(xiàn)過奇數(shù)(放在回文中間,結(jié)果累加1)實(shí)現(xiàn)代碼:
public class Solution {    public int LongestPalindrome(string s) {        if(string.IsNullOrWhiteSpace(s)){    		return 0;    	}    	    	var dict = new Dictionary<char, int>();    	    	var len = s.Length;    	for (var i = 0;i < len; i++){    		if(!dict.ContainsKey(s[i])){    			dict.Add(s[i], 1);    		}    		else{    			dict[s[i]] ++;    		}    	}    	    	int maxLen = 0;    	bool hasMid = false;    	foreach (var k in dict.Keys){    		if(dict[k] % 2 == 0){    			maxLen += dict[k];    		}else{    			hasMid = true;    			if(dict[k] - 1 > 1){    				maxLen += dict[k] - 1;    			}    		}    	}    	    	if(hasMid){    		maxLen ++;    	}    	    	return maxLen;    }}
發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 阳泉市| 文山县| 稻城县| 安阳县| 禹城市| 濉溪县| 九江市| 康保县| 荣成市| 南投县| 龙海市| 利川市| 塔城市| 海城市| 梓潼县| 张家界市| 翁牛特旗| 新龙县| 昌江| 保亭| 长宁区| 陇西县| 商丘市| 板桥市| 安徽省| 绥阳县| 宜春市| 贺兰县| 瑞金市| 吉木乃县| 余干县| 黎川县| 宁国市| 彭泽县| 吴江市| 凤翔县| 嘉善县| 喀什市| 芦溪县| 利津县| 天台县|