【Leetcode】409. Longest Palindrome

来源:互联网 发布:公安 软件代理加盟 编辑:程序博客网 时间:2024/05/21 06:48

思路:

用一个Set存储前面出现过的字母,遍历整个字符串,如果Set中没有出现过,则加入Set,否则移除该字符并加二计数,最后再判断是否Set为空,若是则计数加一。

public class Solution {    public int longestPalindrome(String s) {        int len = s.length();        int result = 0;        Set<Character> set = new HashSet<Character>();        for (int i = 0; i < len; i++) {            if (!set.contains(s.charAt(i)))                set.add(s.charAt(i));            else {                set.remove(s.charAt(i));                result += 2;            }        }        if (!set.isEmpty())            result++;        return result;    }}

Runtime:23ms

1 0
原创粉丝点击