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. 給一個字符串,判斷其字符所能組成的回文的最大長度。
依然是統(tǒng)計每個字符的出現(xiàn)次數(shù),在根據(jù)不同的次數(shù)為結(jié)果加上不同的值。
public int longestPalindrome(String s) { if (s.length() == 0) return 0; if (s.length() == 1) return 1; int[] recordLow = new int[26]; int[] recordUp = new int[26]; int count = 0; boolean extra = false; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c - 'a' >= 0) recordLow[c - 'a']++; else recordUp[c - 'A']++; } for (int i = 0; i < 26; i++) { if (recordLow[i] % 2 == 0) count += recordLow[i] / 2; else { count += (recordLow[i] - 1) / 2; extra = true; } if (recordUp[i] % 2 == 0) count += recordUp[i] / 2; else { count += (recordUp[i] - 1) / 2; extra = true; } } if (extra) return count * 2 + 1; else return count * 2; }新聞熱點
疑難解答