标签:for ddn use 统计 ace math char rar tco
一:解题思路
解题方法:遍历一遍原始字符串,统计每个字母出现的次数,并统计有多少个奇数的字母。那么最后用不上的字母个数为奇数字母个数减1,最后减去它和0之间的最大值即可。Time:O(n),Space:O(k)
二:完整代码示例 (C++版和Java版)
C++:
class Solution { public: int max(int a, int b) { return a > b ? a : b; } int longestPalindrome(string s) { int d[256] = {0}; int oddNum = 0; for (int i = 0; i < s.size(); i++) { d[s[i]]++; } for (int i = 0; i < 256; i++) { if (d[i] % 2 == 1) oddNum++; } int unUsed = max(0,oddNum-1); return s.length() - unUsed; } };
C++11:
class Solution { public: int max(int a, int b) { return a > b ? a : b; } int longestPalindrome(string s) { int d[256] = {0}; int oddNum = 0; for (auto c : s) { d[c]++; } for (auto count : d) { if (count % 2 == 1) oddNum++; } int unUsed = max(0,oddNum-1); return s.length() - unUsed; } };
Java:
class Solution { public int longestPalindrome(String s) { int[] d=new int[256]; int oddNum=0; for(char c:s.toCharArray()) d[c]++; for(int count:d) if(count%2==1) oddNum++; int unUsed=Math.max(0,oddNum-1); return s.length()-unUsed; } }
标签:for ddn use 统计 ace math char rar tco
原文地址:https://www.cnblogs.com/repinkply/p/12506787.html