赞
踩
简单
哈希表记数
哈希表记数
给你一份『词汇表』(字符串数组) words
和一张『字母表』(字符串) chars
。
假如你可以用 chars
中的『字母』(字符)拼写出 words
中的某个『单词』(字符串),那么我们就认为你掌握了这个单词。
注意:每次拼写时,chars
中的每个字母都只能用一次。
返回词汇表 words
中你掌握的所有单词的 长度之和。
输入:words = ["cat","bt","hat","tree"], chars = "atach"
输出:6
解释:
可以形成字符串 "cat" 和 "hat",所以答案是 3 + 3 = 6。
输入:words = ["hello","world","leetcode"], chars = "welldonehoneyr"
输出:10
解释:
可以形成字符串 "hello" 和 "world",所以答案是 5 + 5 = 10。
1 <= words.length <= 1000
1 <= words[i].length, chars.length <= 100
所有字符串中都仅包含小写英文字母
遇到有提示字符串仅包含小写(或者大写)英文字母的题,
都可以试着考虑能不能构造长度为26的每个元素分别代表一个字母的数组,来简化计算
对于这道题,用数组c来保存字母表里每个字母出现的次数
如法炮制,再对词汇表中的每个词汇都做一数组w,比较数组w与数组c的对应位置
class Solution(object): def countCharacters(self, words, chars): """ :type words: List[str] :type chars: str :rtype: int """ res = 0 for word in words: # for i in word: # if word.count(i)<=chars.count(i): # flag = 1 # continue # else: # flag = 0 # break # if flag == 1: # res += len(word) if all(word.count(i)<=chars.count(i) for i in word): res += len(word) return res
public class Solution { public int countCharacters(String[] words, String chars) { int[] c = new int[26]; for(char cc:chars.toCharArray()) { c[(int)cc-'a']+=1; } int res = 0; a: for(String word:words) { int[] w = new int[26]; for(char ww:word.toCharArray()) { w[(int)ww-'a']+=1; } for(int i=0;i<26;i++) { if(w[i]>c[i]) { continue a; } } res += word.length(); } return res; } }
class Solution { public int countCharacters(String[] words, String chars) { int[] abc = new int[26]; for (char ch : chars.toCharArray()) { int index = ch - 'a'; abc[index] += 1; } int sumlen = 0; a: for (String word : words) { int[] sub = abc.clone();// 注意这里 需要用拷贝,如果int[] sub = abc 指定的是同一个对象, int len = 0; for (char cha : word.toCharArray()) { int c = cha - 'a'; if (sub[c] == 0) { len = 0; continue a; } else { len += 1; sub[c] -= 1; } } sumlen += len; } return sumlen; } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。