Problem
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.
NoticeAssume the length of given string will not exceed 1010.
ExampleGiven s = "abccccdd" return 7
One longest palindrome that can be built is "dccaccd", whose length is 7.
Solutionpublic class Solution { /* * @param s: a string which consists of lowercase or uppercase letters * @return: the length of the longest palindromes that can be built */ public int longestPalindrome(String s) { // write your code here int res = 0; //Use HashMap to store occurrence, when it"s even, res adds 2 and map deletes the key Mapmap = new HashMap<>(); for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); if (map.containsKey(ch)) { map.remove(ch); res += 2; } else { map.put(ch, 1); } } if (res < s.length()) res += 1; return res; } }
文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。
轉載請注明本文地址:http://m.specialneedsforspecialkids.com/yun/68259.html
摘要:是左閉右開區間,所以要。,要理解是和之間只有一個元素。循環每次的時候,都要更新子串更大的情況。補一種中點延展的方法循環字符串的每個字符,以該字符為中心,若兩邊為回文,則向兩邊繼續延展。循環返回長度最長的回文串即可。 Problem Given a string S, find the longest palindromic substring in S. You may assume ...
摘要:解題思路我們發現結果其實就是字符的偶數個數是否有單一的字符,如果有就加把單一字符放在回文中間,如果沒有就加字母區分大小寫,代碼 Longest PalindromeGiven a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that...
摘要:題目要求輸入一個字符串,計算用這個字符串中的值構成一個最長回數的長度是多少。直觀來看,我們立刻就能想到統計字符串中每個字符出現的次數,如果該字符出現次數為偶數,則字符一定存在于回數中。這個細節需要注意。 題目要求 Given a string which consists of lowercase or uppercase letters, find the length of the...
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...
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...
閱讀 2021·2021-09-30 09:53
閱讀 1860·2021-09-24 09:48
閱讀 1768·2019-08-30 14:01
閱讀 2180·2019-08-29 18:35
閱讀 1259·2019-08-26 18:27
閱讀 2993·2019-08-26 12:12
閱讀 960·2019-08-23 17:16
閱讀 954·2019-08-23 15:31