刷题感悟 - Longest Palindrome

最近死磕较高难度的题目 深感自己的基本数据结构掌握不够熟练 因此 刷题较慢了些

刷了一道简单的题目涨涨自信

题目:Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters.

This is case sensitive, for example "Aa" is not considered a palindrome here.

思路 :这题要求对称数 的长度 ,如果采用二维数组来计数在代码上和之间复杂度上麻烦了 因此用map的形式来存储char 遍历一遍 相同的删掉并计数 ,

 要考虑特殊情况:刚好长度为字符串长度 

 Map在比较过程中 能有效的节约时间 

代码如下

    public int longestPalindrome(String s) {
        // Write your code here
        if(s.length()==0)return 0;
        char[] chs = s.toCharArray();
        int count=0;
        Map<Character,String > keys=new HashMap<>();
        for(char ch:chs){
            if(keys.containsKey(ch)){
                count++;
                keys.remove(ch);
            }else{
                keys.put(ch,null);
            }
        }if(s.length()==count*2)return count*2;
        return 2*count+1;
    }

 

posted @ 2017-08-20 19:15  小哈是只笨青蛙  阅读(139)  评论(0编辑  收藏  举报