Учитывая строку, которая состоит из строчных или прописных букв, найдите длину самых длинных палиндромов, которые можно построить с помощью этих букв.
Это чувствительно к регистру, например, "Aa" здесь не считается палиндромом.
Примечание:
Предположим, что длина данной строки не будет превышать 1 010.
Пример:
Ввод: "abccccdd"
Выход: 7
Пояснение:
Один из самых длинных палиндромов, который может быть построен, это "dccaccd", длина которого равна 7.
Мой код работает для простых вводов, таких как "abccccdd"
и "banana"
, но не работает для "civilwartestingwhetherthatnaptionoranynartionsoconceivedandsodedicatedcanlongendureWeareqmetonagreatbattlefiemldoftzhatwarWehavecometodedicpateaportionofthatfieldasafinalrestingplaceforthosewhoheregavetheirlivesthatthatnationmightliveItisaltogetherfangandproperthatweshoulddothisButinalargersensewecannotdedicatewecannotconsecratewecannothallowthisgroundThebravelmenlivinganddeadwhostruggledherehaveconsecrateditfaraboveourpoorponwertoaddordetractTgheworldadswfilllittlenotlenorlongrememberwhatwesayherebutitcanneverforgetwhattheydidhereItisforusthelivingrathertobededicatedheretotheulnfinishedworkwhichtheywhofoughtherehavethusfarsonoblyadvancedItisratherforustobeherededicatedtothegreattdafskremainingbeforeusthatfromthesehonoreddeadwetakeincreaseddevotiontothatcauseforwhichtheygavethelastpfullmeasureofdevotionthatweherehighlyresolvethatthesedeadshallnothavediedinvainthatthisnationunsderGodshallhaveanewbirthoffreedomandthatgovernmentofthepeoplebythepeopleforthepeopleshallnotperishfromtheearth"
. Я не уверен, как отладить это.
class Solution {
public int longestPalindrome(String s) {
Map<Character, Integer> map = new HashMap<>();
char[] carr = s.toCharArray();
Arrays.sort(carr);
int leftInd = 0;
int rightInd = 0;
for(int i=0; i<carr.length; i++){
if(map.containsKey(carr[i]))
continue;
else
map.put(carr[i], 1);
}
for(int i=0; i<carr.length-1; i++){
for(int j=i+1; j<carr.length; j++){
if(carr[i]==carr[j]){
if(map.get(carr[i])==null)
continue;
carr[j] = Character.MIN_VALUE;
int count = map.get(carr[i]);
map.put(carr[i], count + 1);
}
}
}
int ans = 0;
int[] oddValArr = new int[map.size()];
int oddInd = 0;
for (Map.Entry<Character, Integer> entry : map.entrySet()) {
Character key = entry.getKey();
Integer value = entry.getValue();
if(value % 2 == 0){
ans += value;
}
else{
oddValArr[oddInd] = value;
oddInd++;
}
}
int biggestOddNum = 0;
for(int i=0; i<oddValArr.length; i++){
if(oddValArr[i] > biggestOddNum)
biggestOddNum = oddValArr[i];
}
return ans + biggestOddNum;
}
}
Выход
655
Ожидаемая
983