classSolution{public:boolcanConstruct(string s,int k){// 右边界为字符串的长度int right = s.size();// 统计每个字符出现的次数int occ[26]={0};for(char ch: s){++occ[ch -'a'];}// 左边界为出现奇数次字符的个数int left =0;for(int i =0; i <26;++i){if(occ[i]%2==1){++left;}}// 注意没有出现奇数次的字符的特殊情况
left =max(left,1);return left <= k && k <= right;}};
上面有点罗嗦
classSolution{public:boolcanConstruct(string s,int k){int hash[26];int n = s.length();memset(hash,0,sizeof(hash));for(int i =0; i < n; i++){
hash[s[i]-'a']++;//(1)}int cnt =0;for(int i =0; i <26; i++){if(hash[i]&1)//(2)
cnt++;}if(k < cnt || k > n)//(3)returnfalse;returntrue;}};