给定一个由小写字母组成的字符串 ,求有多少小写字母出现了至少 次。
,
import java.util.*; public class Solution { //36ms 10556KB //数组存储 public int howMany (String S, int k) { int[] cnt = new int[26]; for (int i = 0; i < S.length(); i++) { int idx = S.charAt(i) - 'a'; cnt[idx]++; } int kTimes = 0; for (int i = 0; i < 26; i++) { if (cnt[i] >= k) kTimes++; } return kTimes; } //59ms 11976KB //map存储 public int howMany1 (String S, int k) { Map<Character, Integer> map = new HashMap<>(); for (int i = 0; i < S.length(); i++) { char ch = S.charAt(i); map.put(ch, map.getOrDefault(ch, 0) + 1); } int cnt = 0; for (Character ch : map.keySet()) { if (map.get(ch) >= k) cnt++; } return cnt; } }
class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param S string字符串 * @param k int整型 * @return int整型 */ unordered_map<char, int> m; int howMany(string S, int k) { // write code here int cnt = 0; for(auto c : S) { if(m[c] == -1) continue; m[c] += 1; if(m[c] == k) { cnt++; m[c] = -1; // 如果某个字母出现的次数等于k次,就把cnt+1,然后将其打上一个印记-1,不再计算此字母出现的次数,以避免cnt重复计算了 // 因为当m[c]=k之后,后面如果再出现同一个字母,再进行一次判断,cnt会将重复算入这个字母,所以需要一个特殊的条件来跳过,出现次数已经等于k的字母 } } return cnt; } };
import java.util.*; public class Solution { public int howMany (String S, int k) { char[] chars = S.toCharArray(); HashMap<Character, Integer> map = new HashMap<>(); for(char c : chars){ map.put(c,map.getOrDefault(c,0) + 1); } int res = 0; Collection<Integer> values = map.values(); for(Integer v : values) if(v >= k) res ++; return res; } }
class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param S string字符串 * @param k int整型 * @return int整型 */ int howMany(string S, int k) { // write code here vector<int> tmp(26, 0); int ans = 0; for(auto& i: S){ tmp[i-'a']++; // 出现次数多余k就不计入 if(tmp[i-'a'] == k) ans++; } return ans; } };
public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param S string字符串 * @param k int整型 * @return int整型 */ public int howMany (String S, int k) { // write code here int[] letters = new int[26]; for(int i = 0; i < S.length(); i++) { letters[S.charAt(i) - 'a']++; } int res = 0; for(int i = 0; i < 26; i++) { if(letters[i] >= k) res++; } return res; } }
from collections import defaultdict class Solution: # 47ms 5156KB def howMany(self , S: str, k: int) -> int: # write code here count_dict = defaultdict(int) count = 0 for i in set(S): count_dict[i] = S.count(i) for i in count_dict: if count_dict[i]>=k: count+=1 return count
from collections import Counter # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param S string字符串 # @param k int整型 # @return int整型 # class Solution: def howMany(self , S: str, k: int) -> int: # write code here d=Counter(S) cnt=0 for key in d: if d[key]>=k: cnt+=1 return cnt