0320-2020-LEETCODE-409-最长回文串(int[26]做字母map)

自己写的,比较快,击败100%

public int longestPalindrome(String s) {
        if (s.length() == 1){
            return 1;
        }
        int[] map1 = new int[26];
        int[] map2 = new int[26];
        for (char c : s.toCharArray()){
            if (c >= 'a'){
                map1[c - 'a']++;
            } else {
                map2[c - 'A']++;
            }
        }
        int countDouble = 0;
        boolean flag = false;
        for (int i = 0; i < 26; i++) {
            countDouble += (map1[i] / 2 + map2[i] / 2);
            if (!flag){
                if (map1[i] % 2 == 1 || map2[i] % 2 == 1){
                    flag = true;
                }
            }
        }
        if (flag){
            countDouble = (countDouble << 1) + 1;
        } else {
            countDouble = countDouble << 1;
        }
    	return countDouble;
    }

学习一下,其他写法。
代码来源:https://leetcode-cn.com/problems/longest-palindrome/solution/javade-2chong-shi-xian-fang-fa-by-sweetiee/

class Solution {
    public int longestPalindrome(String s) {
      int[] cnt = new int[58];
      for (char c : s.toCharArray()) {
        cnt[c - 'A'] += 1;
      }

      int ans = 0;
      for (int x: cnt) {
        // 字符出现的次数最多用偶数次。
        ans += x - (x & 1);
      }
      // 如果最终的长度小于原字符串的长度,说明里面某个字符出现了奇数次,那么那个字符可以放在回文串的中间,所以额外再加一。
      return ans < s.length() ? ans + 1 : ans;  
    }
}
class Solution {
    public int longestPalindrome(String s) {
      Map<Integer, Integer> count = s.chars().boxed()
            .collect(Collectors.toMap(k -> k, v -> 1, Integer::sum));

      int ans = count.values().stream().mapToInt(i -> i - (i & 1)).sum();
      return ans < s.length() ? ans + 1 : ans;
    }
}

Java8的流式风格写法。小数据集上用stream上速度比较慢。

class Solution {
    public int longestPalindrome(String s) {
      Map<Integer, Integer> count = s.chars().boxed()
            .collect(Collectors.toMap(k -> k, v -> 1, Integer::sum));

      int ans = count.values().stream().mapToInt(i -> i - (i & 1)).sum();
      return ans < s.length() ? ans + 1 : ans;
    }
}
发布了98 篇原创文章 · 获赞 0 · 访问量 2192

猜你喜欢

转载自blog.csdn.net/weixin_43221993/article/details/104962843