Java HashSet solution

  • 0

    I take the advantage of HashSet to help me with counting the available characters from the given string.

    It is possible to make use boolean[] array instead. The size of our array will depend on the potential characters that may appear in the given string. In this problem, it seems only A - Z and a - z will appear. So that it is OK to initialize our boolean array with the size of 52.

        public int longestPalindrome(String s) {
            if (s == null || s.length() == 0) return 0;
            Set<Character> set = new HashSet<>();
            int count = 0;
            for (int i = 0; i < s.length(); i++) {
                char c = s.charAt(i);
                // true if this set did not already contain the specified element
                if (!set.add(c)) {  
                    count += 2;
            return count + (set.size() > 0 ? 1 : 0);

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.