First Thoughts: using character counts to determine palindrome validity. retrieving counts, so either array using ascii or hashmap for O(1). can only accept 1 once, if odd count which is greater than 1, add count-1.
My Solution:
class Solution {
public int longestPalindrome(String s) {
boolean acceptedOdd = false;
int maxLength = 0;
HashMap<Character, Integer> chars = new HashMap<>();
for (char c : s.toCharArray()) {
chars.putIfAbsent(c, 0);
chars.put(c, chars.get(c)+1);
}
if (chars.keySet().size()==1) return s.length();
for (char ch : chars.keySet()) {
int div = chars.get(ch)/2;
maxLength += div*2;
}
if (s.length()!=maxLength) maxLength++;
return maxLength;
}
}
LeetCode Version:
class Solution {
public int longestPalindrome(String s) {
int[] count = new int[128];
for (char c: s.toCharArray())
count[c]++;
int ans = 0;
for (int v: count) {
ans += v / 2 * 2;
if (ans % 2 == 0 && v % 2 == 1)
ans++;
}
return ans;
}
}
그 동안 홀수를 한 번도 안더했는지 더했는지 boolean flag를 통해서 확인할 수도 있지만 accumulator가 짝수인지 홀수인지를 통해 홀수를 더한 적이 있는지 확인이 가능하다.
물론 알고있겠지만 ascii를 index로 사용 가능하다.
Educational material is always on your blog that would be quite recommended. The students would able to fix their educational problems and explore coding. Really admire your tremendous recommendation on https://bestwritingsclues.com/reviews/essaywriter-review/ blog please do share related material always would like to share with others.