0
点赞
收藏
分享

微信扫一扫

409. 最长回文串

_鱼与渔_ 2022-03-15 阅读 31

思路:

  public int longestPalindrome(String s) {
      //哈希数组
      int[] hash= new int[58]; // 'Z' - 'a'
      int l = s.length();
      for(int i = 0; i < l; i++) {
          hash[s.charAt(i)-'A']++;
      }
      int res = 0;
      // 判断是否存在奇数个数的字母--只要存在,最后的长度需加一
      boolean tf = false;
      for(int i = 0; i < 58; i++) {
          if((hash[i] & 1) == 0) {
              //偶数
              res = res + hash[i]; 
          } else {
              //奇数减一
              res = res + hash[i] - 1; 
              tf = true;              
          }            
      }
      return tf == true ? res+1 : res;
    }
举报

相关推荐

0 条评论