🌗 409. 最长回文串

吞佛童子2022年10月10日
  • algorithm
  • String
  • 回文串
小于 1 分钟

🌗 409. 最长回文串

难度: 🌗

问题描述

img_1.png


解法

class Solution {
    public int longestPalindrome(String s) {
        // 思路:
        // 遍历,遇到 2 个相同的字符 res += 2
        // 最后判断有没有单独的,如果有,res ++
        HashSet<Character> set = new HashSet<>();
        int res = 0;
        for(char c: s.toCharArray()) {
            if(set.contains(c)) {
                set.remove(c);
                res += 2;
            } else {
                set.add(c);
            }
        }
        if(!set.isEmpty()) {
            res ++;
        }
        return res;
    }
}

输出

img.png

上次编辑于: 2022/10/10 下午8:43:48
贡献者: liuxianzhishou