Longest Palindrome: ans%2==1

Jay·2022년 5월 24일
0

Grind 120

목록 보기
15/38
post-thumbnail


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;
    }
}

Catch Point:

  1. 그 동안 홀수를 한 번도 안더했는지 더했는지 boolean flag를 통해서 확인할 수도 있지만 accumulator가 짝수인지 홀수인지를 통해 홀수를 더한 적이 있는지 확인이 가능하다.

  2. 물론 알고있겠지만 ascii를 index로 사용 가능하다.

1개의 댓글

comment-user-thumbnail
2022년 12월 16일

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.

답글 달기