0320-2020-LEETCODE-409- longest palindromic sequence (int [26] do letters Map)

Write your own, faster, beat 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;
    }

Learn about other writing.
Code Source: 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 streaming writing style. Stream with slow speed on a small data set.

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;
    }
}
Published 98 original articles · won praise 0 · Views 2192

Guess you like

Origin blog.csdn.net/weixin_43221993/article/details/104962843