加载中...
1160-拼写单词(Find Words That Can Be Formed by Characters)
发表于:2021-12-03 | 分类: 简单
字数统计: 611 | 阅读时长: 2分钟 | 阅读量:

原文链接: https://leetcode-cn.com/problems/find-words-that-can-be-formed-by-characters

英文原文

You are given an array of strings words and a string chars.

A string is good if it can be formed by characters from chars (each character can only be used once).

Return the sum of lengths of all good strings in words.

 

Example 1:

Input: words = ["cat","bt","hat","tree"], chars = "atach"
Output: 6
Explanation: The strings that can be formed are "cat" and "hat" so the answer is 3 + 3 = 6.

Example 2:

Input: words = ["hello","world","leetcode"], chars = "welldonehoneyr"
Output: 10
Explanation: The strings that can be formed are "hello" and "world" so the answer is 5 + 5 = 10.

 

Constraints:

  • 1 <= words.length <= 1000
  • 1 <= words[i].length, chars.length <= 100
  • words[i] and chars consist of lowercase English letters.

中文题目

给你一份『词汇表』(字符串数组) 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. 1 <= words.length <= 1000
  2. 1 <= words[i].length, chars.length <= 100
  3. 所有字符串中都仅包含小写英文字母

通过代码

高赞题解

解题思路:

直接统计字母表 chars 中每个字母出现的次数,然后检查词汇表 words 中的每个单词,如果该单词中每个字母出现的次数都小于等于词汇表中对应字母出现的次数,就将该单词长度加入答案中。

图解:

图解

代码:

[-python]
class Solution: def countCharacters(self, words: List[str], chars: str) -> int: ans = 0 cnt = collections.Counter(chars) for w in words: c = collections.Counter(w) if all([c[i] <= cnt[i] for i in c]): ans += len(w) return ans

统计信息

通过次数 提交次数 AC比率
60632 88247 68.7%

提交历史

提交时间 提交结果 执行时间 内存消耗 语言
上一篇:
1039-多边形三角剖分的最低得分(Minimum Score Triangulation of Polygon)
下一篇:
1040-移动石子直到连续 II(Moving Stones Until Consecutive II)
本文目录
本文目录