leetcode 最长回文串
回文串的定义
两种回文串:
奇数:字母的出现频次
偶数:字母的出现频次
题目
思路
哈希记录每个字符的个数,统计偶数的和奇数的字符,偶数的字符个数加1则为当前最大的回文串。
代码:
class Solution { public: int longestPalindrome(string s) { int hash_map[52]; memset(hash_map,0,sizeof(hash_map)); //统计字符串中每个字符出现的次数 for(int i = 0;i<s.length();i++) { char c = s[i]; if(c>='a'&&c<='z') { hash_map[c-'a']++; } else if (c>='A'&&c<='Z') { hash_map[c-'A'+26]++; //总共用52个空间记录字符串的个数 } } int res = 0; int odd_flag = 0; for(int i =0;i<52;i++) // 统计所有字符串的个数 如果有某个字符的个数为为奇数,则减去一,并标记为有奇数字符 { res+= hash_map[i]; if(res%2!=0) { res--; odd_flag = 1; } } if (odd_flag == 1) // 从奇数的字符集中随意挑选一个加到偶数字符串的中间 组成最大的回文串 { res++; } return res; } };
以大多数人努力程度之低,根本轮不到去拼天赋~