LeetCode-最长回文串-简单

这篇博客探讨了如何解决寻找给定字符串中最长回文子串的问题。提供了三种不同的Java实现方法,包括排序找两两相同点、哈希存储次数以及优化后的数组方法。所有方法都考虑了大小写字母并优化了时间复杂度,适用于处理长度不超过1010的字符串。示例输入和输出展示了算法的有效性,最长回文串的长度为7。
摘要由CSDN通过智能技术生成

标题:409最长回文串-简单

题目

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

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

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

示例1

输入:
"abccccdd"

输出:
7

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

代码Java

// 排序  找两两相同点  - 2ms
public int longestPalindrome(String s) {
    int result = 0;
    char[] chars = s.toCharArray();
    Arrays.sort(chars);
    for (int i = 1; i < chars.length; i++) {
        if (chars[i] == chars[i-1]) {
            i++;
            result += 2;
        }
    }
    if (result < chars.length)
        return result + 1;
    else return result;
}
// 哈希存储次数 - 内存使用少 但是还是慢
public int longestPalindrome1(String s) {
    int[] big = new int[26];
    int[] small = new int[26];
    int result = 0;
    for (int i = 0; i < s.length(); i++) {
        char ch = s.charAt(i);
        if (ch >= 'a') {
            small[ch - 97] ++;
        } else {
            big[ch - 65] ++;
        }
    }
    for (int i = 0; i < 26; i++) {
        result += big[i] / 2 * 2;
        result += small[i] / 2 * 2;
    }
    if (result < s.length())
        return result + 1;
    else return result;
}
// 优化数组
public int longestPalindrome2(String s) {
    int[] count = new int[128];
    int length = s.length();
    for (int i = 0; i < length; ++i) {
        char c = s.charAt(i);
        count[c]++;
    }
    int ans = 0;
    for (int v: count) {
        ans += v / 2 * 2;
    }
    if (ans < length)
        return ans + 1;
    return ans;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

SoaringW

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值