ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

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

2020-03-17 10:00:02  阅读:254  来源: 互联网

标签:word str chars cat 力扣 words ans 1160 0317


<>

题目描述


给你一份『词汇表』(字符串数组) 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)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

 

 

总结


 

标签:word,str,chars,cat,力扣,words,ans,1160,0317
来源: https://www.cnblogs.com/remly/p/12508752.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有