[ 力扣活动0317 ] 1160. 拼写单词

<>

题目描述


给你一份『词汇表』(字符串数组) 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. 所有字符串中都仅包含小写英文字母

我的思路 


取words当中的一个词"cat"来说明,chars = "atach"

1.扫描"cat",如果"cat"中的字符出现在chars中,则在chars中把这个字符置为星号(*)

2.扫描"cat"结束之后看看是否"cat"用到了。

class Solution(object):
    def countCharacters(self, words, chars):
        """
        :type words: List[str]
        :type chars: str
        :rtype: int
        """        
        ans = 0
        for word in words:
            chars_ = chars
            test = len(word)
            for w in word:
                idx = chars_.find(w)
                if idx == -1:
                    test-=1
                    break
                chars_ = chars_[:idx] + "*"+chars_[idx+1:]
            if test == len(word):
                ans+=len(word)
        return ans

 

题解1 


用 word = "cat" ,chars = "atach" 来说明

1.换个方向思考,假设我们把 word 和 chars 排个序:

word = "act" 

chars = "aacht"

2.纵向对比一下发现,必须有:chars.count("a") >= word.count(a) , 否则不能拼写这个单词。

class Solution(object):
    def countCharacters(self, words, chars):
        """
        :type words: List[str]
        :type chars: str
        :rtype: int
        """
        ans = 0
        for w in words:
            for i in w:
                if w.count(i) > chars.count(i):
                    break
            else:
                ans+=len(w)
        return ans
--摘自大佬的答案

题解2 


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

作者:smoon1989
链接:https://leetcode-cn.com/problems/find-words-that-can-be-formed-by-characters/solution/tong-ji-python3-by-smoon1989/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

 

总结


猜你喜欢

转载自www.cnblogs.com/remly/p/12508752.html
今日推荐