题1 最长回文串
描述
给定一个包含大写字母和小写字母的字符串,找到通过这些字母构造成的最长的回文串。
在构造过程中,请注意区分大小写。比如 “Aa” 不能当做一个回文字符串。
注意:
假设字符串的长度不会超过 1010。
示例 1:
输入:
“abccccdd”
输出:
7
解释:
我们可以构造的最长的回文串是"dccaccd", 它的长度是 7。
方法1 用HashMap
思路:自己想的方法,内存和时间消耗比较大。首先用hashmap存字符串中每个字母的个数。字母为偶数,则全部可以用来做回文串,若字母为奇数,则要减1剩余的可以用来做回文串。奇数字母中只有一个字母可以用奇数做回文串,多出来的位于中间,所以结果+1。
class Solution {
public int longestPalindrome(String s) {
int len = s.length();
boolean flag = false;
Map<Character, Integer> map= new HashMap<>();
int cnum = 0;
for(char c: s.toCharArray()){
if(!map.containsKey(c)){
map.put(c, 1);
}else{
map.put(c, map.get(c)+1);
}
}
int result = 0;
for(Map.Entry<Character, Integer> entry: map.entrySet())
{
cnum += 1;
if(entry.getValue() % 2 == 0){
result += entry.getValue();
}else{
flag = true;
result += entry.getValue()-1;
}
}
if(cnum == 1){
return len;
}
if(flag){
return result+1;
}else{
return result;
}
}
}
方法2 用数组统计字母数
class Solution {
public int longestPalindrome(String s) {
int[] count = new int[128];
for (char c: s.toCharArray())
count[c]++;
int ans = 0;
for (int v: count) {
ans += v / 2 * 2; //除2把奇数的去掉了
if (v % 2 == 1 && ans % 2 == 0) //奇数的+1
ans++;
}
return ans;
}
}