409、最长回文串

  1. 409、 最长回文串
    1. 示例 1:
  2. 题解
    1. 1、统计每个字符的个数,在计算偶数对

409、 最长回文串

给定一个包含大写字母和小写字母的字符串,找到通过这些字母构造成的最长的回文串。

在构造过程中,请注意区分大小写。比如 “Aa” 不能当做一个回文字符串。

注意:
假设字符串的长度不会超过 1010。

示例 1:

输入:
"abccccdd"

输出:
7

解释:
我们可以构造的最长的回文串是"dccaccd", 它的长度是 7。

题解

1、统计每个字符的个数,在计算偶数对

class Solution {
    public int longestPalindrome(String s) {
        int[] chs = new int[128];
        for (char ch : s.toCharArray()) {
            chs[ch]++;
        }
        int len = 0;
        for (int i = 0;i < 128;i++) {
            len += (chs[i]/2);
        }
        len *= 2;
        if (len < s.length()) {
            len += 1;
        }
        return len;
    }
}
  • java8 Stream流 & lambda表达式
class Solution {
    public int longestPalindrome(String s) {
        // ChasSequence#chars()
        // IntStream#Boxed()
        // Stream#collect()
        // Collectors#toMap()
        Map<Integer, Integer> count = s.chars().boxed()
            .collect(Collectors.toMap(k -> k, v -> 1, Integer::sum));
        // Stream#mapToInt()
        int ans = count.values().stream().mapToInt(i -> i - (i & 1)).sum();
        return ans < s.length() ? ans + 1 : ans;
    }
}

转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 1056615746@qq.com

💰

Title:409、最长回文串

Count:265

Author:攀登

Created At:2020-07-26, 00:19:44

Updated At:2024-06-15, 15:52:32

Url:http://jiafeimao-gjf.github.io/2020/07/26/409%E3%80%81%E6%9C%80%E9%95%BF%E5%9B%9E%E6%96%87%E4%B8%B2/

Copyright: 'Attribution-non-commercial-shared in the same way 4.0' Reprint please keep the original link and author.

×

Help us with donation