LeetCode_数据结构_最长回文串

最长回文串

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

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

示例 1:

输入:s = “abccccdd”
输出:7
解释:
我们可以构造的最长的回文串是"dccaccd", 它的长度是 7。
示例 2:

输入:s = “a”
输入:1
示例 3:

输入:s = “bb”
输入: 2

(上述题目来源于LeetCode)

解法一(哈希表)
class Solution {
    public int longestPalindrome(String s) {
        //使用哈希表存储每个字符及其出现的次数,然后遍历哈希表
        //如果出现次数为偶数的字符,一定会全部出现在最长回文串中,
        //然后将该字符在哈希表中的出现次数改为0
        //如果出现次数为奇数且大于1的字符,一定有出现次数减1的该字符出现在最长回文串中
        //然后将该字符在哈希表中的出现次数改为1
        //最后再遍历一次哈希表,如果有出现次数为1的字符,那么最长回文串的长度加1
        int n = s.length();
        int count = 0;
        Map<Character,Integer> hashmap = new HashMap<>();
        for(int i = 0;i < n;i++){
            char ch = s.charAt(i);
            hashmap.put(ch,hashmap.getOrDefault(ch,0) + 1);
        }
 
        for(Character i : hashmap.keySet()){
            int num = hashmap.get(i);
            if(num > 1){
                if(num % 2 == 0){
                    count = count + num;
                    // hashmap.remove(i);
                    hashmap.put(i,0);
                }else{
                    count = count + num - 1;
                    hashmap.put(i,1);
                }
            }
        }
        // if(hashmap.size() > 0){
        //     count++;
        // }
        for(Character i : hashmap.keySet()){
            int num = hashmap.get(i);
            if(num > 0){
                count++;
                break;
            }
        }
        return count;
    }
}

#####解法二

class Solution {
    public int longestPalindrome(String s) {
        int count = 0;
        int[] list = new int[58];
        for(int i = 0;i < s.length();i++){
            char ch = s.charAt(i);
            list[ch - 'A']++;
        } 
        for(int i : list){
            if(i > 0){
                if(i % 2 == 0){
                    count = count + i;
                }else{
                    count = count + i / 2 * 2;
                    if(count % 2 == 0){
                        count++;
                    }
                }
            }
        }
        return count;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值