给定一个包含大写字母和小写字母的字符串,找到通过这些字母构造成的最长的回文串。 在构造过程中,请注意区分大小写。比如 "Aa" 不能当做一个回文字符串。 复制代码
示例:
输入: "abccccdd" 输出: 7 解释: 我们可以构造的最长的回文串是"dccaccd", 它的长度是 7。 复制代码
思考:
这题先用一个Map记录每个字符出现的次数。 接着遍历Map,次数为偶数的可以接加入结果,次数为奇数的将次数减1后加入结果。 用一个布尔值记录一下是否有奇数次数的元素。 遍历Map结束后,如果有奇数次数元素,可以将一个奇数次数数字放在字符串中间,回文串长度加1。 复制代码
实现:
class Solution {
public int longestPalindrome(String s) {
int result = 0;
boolean isHas = false;
char[] strArray = s.toCharArray();
Map<Character, Integer> time = new HashMap();
for (int count = 0; count < strArray.length; count++) {
if (time.get(strArray[count]) == null) {
time.put(strArray[count], 1);
} else {
time.put(strArray[count], time.get(strArray[count]) + 1);
}
}
Set<Character> set = time.keySet();
for (Character character : set) {
int times = time.get(character);
if (times % 2 == 0) {
result += (times);
} else if (times % 2 == 1) {
isHas = true;
result += ((times - 1));
}
}
if (isHas) {
result += 1;
}
return result;
}
}复制代码
以上所述就是小编给大家介绍的《LeetCode每日一题:最长回文串(No.409)》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:- 回文算法(JavaScript)
- 让我们一起啃算法----回文数
- 每日一道 LeetCode (3):回文数
- java算法题:最长回文串
- 每天一道leetcode234-回文链表
- 判断单链表回文的三种方法
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
The Master Switch
Tim Wu / Knopf / 2010-11-2 / USD 27.95
In this age of an open Internet, it is easy to forget that every American information industry, beginning with the telephone, has eventually been taken captive by some ruthless monopoly or cartel. Wit......一起来看看 《The Master Switch》 这本书的介绍吧!