当前位置:   article > 正文

【LeetCode每日一题】拼写单词_有一个字符串数组words和一个字符串chars

有一个字符串数组words和一个字符串chars

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

来源:力扣(LeetCode)

Python3 1

思路:依次遍历数组中的字符串,遍历这个字符串中的字符,在chars中寻找,如果存在就删除掉第一个字符,否则返回False。如果遍历完chars之后还有剩余字符,则返回True。

class Solution:
    def m(self, chars1:str, chars2:str)->bool:
        for i in chars1 :
            t = chars2.find(i)
            if t >= 0:
                #print(i)
                chars2 = chars2.replace(i,"", 1)
            else:
                return False
        if len(chars2)>=0:
            return True
        return False

    def countCharacters(self, words: List[str], chars: str) -> int:
        num = 0
        for s in words:
            temp = chars
            #print(s)
            if self.m(s, temp):
                num = num+len(s)
        return num
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

Python3 2

思路:遍历words数组,对于其中的每一个字符串A,遍历chars中的每个字符分别在A中和chars中出现的数目,如果后者较大,则设flag为1,代表能够拼出A单词,否则记为0,表示不能包含此单词。最终累加长度。

class Solution(object):
    def countCharacters(self, words, chars):
        ans = 0
        for w in words:
            for i in w:
                if w.count(i) <= chars.count(i):
                    flag = 1
                    continue
                else:
                    flag = 0
                    break
            if flag == 1:
                ans+=len(w)
        return ans
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/705383
推荐阅读
相关标签
  

闽ICP备14008679号