• 刷题感悟


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

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

    题目: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;
        }
  • 相关阅读:
    E
    牛客比赛—身体训练
    前缀和例题
    欧拉函数模板
    3.30训练题
    poj1321棋盘问题
    记set学习
    B. K-th Beautiful String
    codeforces1293C
    LightOJ 1370 Bi-shoe and Phi-shoe
  • 原文地址:https://www.cnblogs.com/zslzz/p/7401035.html
Copyright © 2020-2023  润新知