leetcode 1160. Find Words That Can Be Formed by Characters 拼写单词

leetcode 1160. Find Words That Can Be Formed by Characters 拼写单词

leetcode 2020年3月 每日一题打卡

题目:
给你一份『词汇表』(字符串数组) 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)
链接:https://leetcode-cn.com/problems/find-words-that-can-be-formed-by-characters

思路: python

细节:

  1. str转换为list:list1 = list.(str1)
  2. list转str: “”.join(list)
  3. 删除列表中某个元素
list1=[1,2,3,3,4,5]
list1.remove(3)
print(list1)
# 输出[1,2,3,4,5]

代码:

class Solution(object):
    def countCharacters(self, words, chars):
        """
        :type words: List[str]
        :type chars: str
        :rtype: int
        """

        ans=0
        for word in words:
            char = list(chars)
            flag = True
            for w in  word:
                if w in char:
                    char.remove(w)
                    continue
                else:
                    flag=False
            if flag:
                ans+=len(word)
        
        return ans
               

本博客为原创作品,欢迎指导,转载请说明出处,附上本文链接,谢谢!

发布了20 篇原创文章 · 获赞 1 · 访问量 198

猜你喜欢

转载自blog.csdn.net/weixin_43973433/article/details/104915788