给你一份『词汇表』(字符串数组) words 和一张『字母表』(字符串) chars。
假如你可以用 chars 中的『字母』(字符)拼写出 words 中的某个『单词』(字符串),那么我们就认为你掌握了这个单词。
注意:每次拼写(指拼写词汇表中的一个单词)时,chars 中的每个字母都只能用一次。
返回词汇表 words 中你掌握的所有单词的 长度之和。
示例 1:
输入:words = ["cat","bt","hat","tree"], chars = "atach"
输出:6
解释:
可以形成字符串 "cat" 和 "hat",所以答案是 3 + 3 = 6。
示例 2:
输入:words = ["hello","world","leetcode"], chars = "welldonehoneyr"
输出:10
解释:
可以形成字符串 "hello" 和 "world",所以答案是 5 + 5 = 10。
方法1
遍历法
机械翻译, 遍历words数组, 变量字符串, 判断chars是否完全包含数组元素
注意: chars 中的每个字母都只能用一次
代码
func countCharacters(_ words: [String], _ chars: String) -> Int {
var result = 0, select = 0, cchar = chars
for i in words {
if i.count > chars.count {
continue
}
cchar = chars
for j in i {
select = 0
if let idx = cchar.firstIndex(of:j) {
cchar.remove(at: idx)
} else {
select = 1
break
}
}
if select != 1 {
result += i.count
}
}
return result;
}
方法2
哈希表
将chars转成字典, 每一个字符做key出现次数做value 进行判断处理
循环判断 出现一次 对应key值的value - 1, 不存在或者value = 0 跳出循环
存在的count相加即可
代码
func countCharacters(_ words: [String], _ chars: String) -> Int {
var result = 0, select = 0, dic = [Character:Int]()
for c in chars {
dic[c] = (dic[c] ?? 0) + 1
}
for i in words {
if i.count > chars.count {
continue
}
select = 0
var tempDic = dic
for j in i {
guard let count = tempDic[j] else {
select = 1
break
}
if count == 0 {
select = 1
break
}
tempDic[j] = count - 1
}
if select != 1 {
result += i.count
}
}
return result;
}
题目来源:力扣(LeetCode) 感谢力扣爸爸 :)
IOS 算法合集地址
网友评论