给定一个包含大写字母和小写字母的字符串 s ,返回 通过这些字母构造成的 最长的回文串 。
在构造过程中,请注意 区分大小写 。比如 "Aa" 不能当做一个回文字符串。
方法一:
- class Solution {
- public int longestPalindrome(String s) {
- if(s.length() == 0){
- return 0;
- }
- HashSet<Character> set = new HashSet<Character>();
- char[] chars = s.toCharArray();
- int count = 0;
- for(int i = 0;i < chars.length;i ++ ){
- if( !set.contains(chars[i]) ){
- set.add(chars[i]);
- }else{
- set.remove(chars[i]);
- ++count;
- }
- }
- return set.isEmpty() ? count*2 : count*2+1;
- }
- }
执行用时:5 ms, 在所有 Java 提交中击败了37.04%的用户
内存消耗:41.4 MB, 在所有 Java 提交中击败了5.03%的用户
通过测试用例:95 / 95
方法二:
- class Solution {
- public int longestPalindrome(String s) {
- int[] count = new int[128];
- int len = s.length();
- for(int i = 0;i < len;i ++){
- char c = s.charAt(i);
- count[c]++;
- }
- int ans = 0;
- for(int num : count){
- ans += num/2*2;
- if(ans % 2 == 0 && num%2 == 1){
- ++ans;
- }
- }
- return ans;
-
- }
- }
执行用时:1 ms, 在所有 Java 提交中击败了100.00%的用户
内存消耗:39.9 MB, 在所有 Java 提交中击败了17.95%的用户
通过测试用例:95 / 95