Java 4-line HashSet & 5-line int[128]


  • 0
    S
    public int longestPalindrome(String s) {
            Set<Character> set = new HashSet<Character>();
            for (int i = 0; i < s.length(); i++)
                if (!set.add(s.charAt(i))) set.remove(s.charAt(i));
            return s.length()-Math.max(set.size()-1, 0);
        }
    
    public int longestPalindrome(String s) {
            int[] array = new int[128];
            int sum = s.length();
            for (int i = 0; i < s.length(); i++)
                sum += (array[s.charAt(i)]++)%2==0 ? -1 : 1;
            return Math.min(sum+1, s.length());
        }
    

Log in to reply
 

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