Shawngbk / Leecode

Questions of Leecode
0 stars 0 forks source link

409. Longest Palindrome #114

Open Shawngbk opened 7 years ago

Shawngbk commented 7 years ago

被加入和删除,最后不再set中存在,则该元素为偶数次。统计最后set中剩下的元素,用字符串长度减去剩下的元素加一则是答案 public class Solution { public int longestPalindrome(String s) { if(s == null) return 0; HashSet set = new HashSet();

    for(int i = 0; i < s.length(); i++) {
        if(set.contains(s.charAt(i))) {
            set.remove(s.charAt(i));
        } else {
            set.add(s.charAt(i));
        }
    }
    if(set.size()>0)
    return s.length()-set.size()+1;
    else
    return s.length()-set.size();
}

}

方法二: public class Solution { public int longestPalindrome(String s) { int[] freq = new int[256]; int count = 0; for (char ch : s.toCharArray()) { freq[ch - 'A'] ++; if (freq[ch - 'A'] == 2) { count += 2; freq[ch - 'A'] = 0; } } if (count < s.length()) count += 1; return count; } }

Shawngbk commented 7 years ago

google