LeetCode刷题の字符串
字符串
125. 验证回文串
给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
说明:本题中,我们将空字符串定义为有效的回文串。
思路:首先利用isalnum函数排除非字母数字,lower/tolower将所有字母转为小写
然后镜像对比处理后的字符串
class Solution {
public:
bool isPalindrome(string s) {
string str;
for(auto num:s)if(isalnum(num))str+=tolower(num);
int len=str.size();
for(int i=0;i<len/2;i++){
if(str[i]!=str[len-1-i]){
return false;
}
}
return true;
}
};
409. 最长回文串
给定一个包含大写字母和小写字母的字符串,找到通过这些字母构造成的最长的回文串。
在构造过程中,请注意区分大小写。比如 “Aa” 不能当做一个回文字符串。
思路:参考
class Solution {
public:
int longestPalindrome(string s) {
int res=0;
unordered_map<char, int> up;
int length = s.size();
for (int i = 0; i < length; i++) {
up[s[i]]++;
}
for (unordered_map<char, int>::iterator it = up.begin(); it != up.end(); it++) {
//判断是否为奇数。如果res为奇数说明已经选中了一个数量为奇数的字符,再遇到奇数数量的字符时需减一。
if((res&1)&&(it->second&1)){
res+=it->second-1;
}
else{
res+=it->second;
}
}
return res;
}
};