摘要:題目要求輸入一個(gè)字符串,計(jì)算用這個(gè)字符串中的值構(gòu)成一個(gè)最長(zhǎng)回?cái)?shù)的長(zhǎng)度是多少。直觀來(lái)看,我們立刻就能想到統(tǒng)計(jì)字符串中每個(gè)字符出現(xiàn)的次數(shù),如果該字符出現(xiàn)次數(shù)為偶數(shù),則字符一定存在于回?cái)?shù)中。這個(gè)細(xì)節(jié)需要注意。
題目要求
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: 7 Explanation: One longest palindrome that can be built is "dccaccd", whose length is 7.
輸入一個(gè)字符串,計(jì)算用這個(gè)字符串中的值構(gòu)成一個(gè)最長(zhǎng)回?cái)?shù)的長(zhǎng)度是多少。
思路和代碼這是一道easy難度的題目,但是一次性寫(xiě)對(duì)也有挑戰(zhàn)。直觀來(lái)看,我們立刻就能想到統(tǒng)計(jì)字符串中每個(gè)字符出現(xiàn)的次數(shù),如果該字符出現(xiàn)次數(shù)為偶數(shù),則字符一定存在于回?cái)?shù)中。但是我們忽略了一點(diǎn),即如果字符中存在一個(gè)額外的單個(gè)字符位于中間,該字符串也能構(gòu)成回?cái)?shù),如aabaa。這個(gè)細(xì)節(jié)需要注意。
下面是O(N)時(shí)間的實(shí)現(xiàn):
public int longestPalindrome(String s) { int[] count = new int[52]; int max = 0; for(char c : s.toCharArray()) { if(c>="a" && c<="z"){ count[c-"a"]++; if(count[c-"a"] % 2 == 0) { max +=2; } } if(c>="A" && c<="Z"){ count[c-"A" + 26]++; if(count[c-"A"+26] % 2 == 0) { max += 2; } } } if(max < s.length()) { max++; } return max; }
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://systransis.cn/yun/73342.html
摘要:判斷一個(gè)能否組成一個(gè)第一次出現(xiàn)增加一,第二次出現(xiàn)減少一。出現(xiàn)偶數(shù)次的最終對(duì)被抵消。出現(xiàn)基數(shù)詞的則會(huì)讓加一。類似于,奇數(shù)個(gè)的那個(gè)單獨(dú)考慮,必須放中間。得到各個(gè)字符一半數(shù)量的長(zhǎng)度數(shù)字的終止條件,利用的對(duì)稱性輸出結(jié)果。 Given a string s, return all the palindromic permutations (without duplicates) of it. R...
Problem Find the largest palindrome made from the product of two n-digit numbers. Since the result could be very large, you should return the largest palindrome mod 1337. Example Input: 2Output: 987Ex...
摘要:最笨的方法就是用的解法,找出所有的,然后再用中判斷回文的方法來(lái)判斷結(jié)果中是否有回文。而中心對(duì)稱點(diǎn)如果是字符,該字符會(huì)是奇數(shù)次,如果在兩個(gè)字符之間,則所有字符都是出現(xiàn)偶數(shù)次。 Palindrome Permutation Given a string, determine if a permutation of the string could form a palindrome. F...
Valid Palindrome Problem Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. Example A man, a plan, a canal: Panama is a palindrome. race a ca...
Problem Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward. Example 1: Input: 121Output: trueExample 2: Input: -121Output: falseExplana...
閱讀 2866·2021-10-21 09:38
閱讀 2764·2021-10-11 10:59
閱讀 3057·2021-09-27 13:36
閱讀 1673·2021-08-23 09:43
閱讀 806·2019-08-29 14:14
閱讀 3044·2019-08-29 12:13
閱讀 3213·2019-08-29 12:13
閱讀 319·2019-08-26 12:24