409. 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.

Note:
Assume the length of given string will not exceed 1,010.

Example:

Input:
"abccccdd"

Output:
7

Explanation:
One longest palindrome that can be built is "dccaccd", whose length is 7.

tips:

  1. 给出一串字符串,然后取这串字符串的字符组成一个新的回文字符串,求回文字符串的最长长度;
  2. 字符串中的字母的个数为奇数的取这个奇数减一,字母的个数为偶数的取这个偶数,最后,如果这个字符串包含个数为奇数的字母还要再加一;
  3. 有两种方式,一种方式使用hashmap(运行时间为25ms),另外一种方式使用hasSet(运行时间是20ms),两种方法实质上是一样的,都弄出来,多种思路吧;

方式一:hashMap方式;

public int longestPalindrome(String s) {
        if(s.length()<=0||s==null)
            return 0;
        if(s.length()==1)
            return 1;
        HashMap<Character,Integer> hashMap=new HashMap<>();
        for(int i=0;i<s.length();i++){
            char c=s.charAt(i);
            if(hashMap.containsKey(c))
                hashMap.put(c,hashMap.get(c)+1);
            else
                hashMap.put(c,1);
        }
        int flag=0;
        int res=0;
        Set<Map.Entry<Character,Integer>> entry=hashMap.entrySet();
        for(Map.Entry<Character,Integer>e:entry){
            if(e.getValue()%2==0)
                res+=e.getValue();
            else
            {
                res+=e.getValue()-1;
                flag=1;
            }
        }
        res+=flag;
        return res;

 方式二:hashSet方式

public int longestPalindrome(String s){
      if(s.length()<=0||s==null)
          return 0;
      if(s.length()==1)
          return 1;
      HashSet<Character> hashSet=new HashSet<>();
      int count=0;
      for(int i=0;i<s.length();i++){
          char c=s.charAt(i);
          if(hashSet.contains(c))
          {
              hashSet.remove(c);
              count++;
          }
          else {
              hashSet.add(c);
          }
      }
      count=hashSet.size()==0?count*2:count*2+1;
      return count;
  }

 

转载于:https://my.oschina.net/yangdongchun/blog/754994

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值