W
e
l
c
o
m
e
: )

python collections类 高性能容器数据类型

counter对象,用于计数

1:计数字符串

import  collections
b=collections.Counter("abcdefg")
结果:
Counter({'a': 1, 'b': 1, 'c': 1, 'd': 1, 'e': 1, 'f': 1, 'g': 1})
使用:

b['a']

结果:

1

2:计数字符串数组

import  collections
c=collections.Counter(['red','blue','black','red','red','black'])
结果:
Counter({'red': 3, 'black': 2, 'blue': 1})
使用:

c['red']

结果:

3

leedcode签到题: 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。
来源:leetcode
链接:https://leetcode-cn.com/problems/find-words-that-can-be-formed-by-characters/

答案1:

思路:count方法,遍历字符串数组,比较words里每个字符串中包含的字母数量与chars包含此字母的数量,若小于则成立,计数器加一,最后比较计数器与words单词的长度,若相等,则成立。

class Solution:
     def countCharacters(self, words, chars):
         num=0
         for i in words:
             count = 0
             l = len(i)
             for j in i:
                 if i.count(j)<=chars.count(j):
                     count+=1
                 else:
                     break
             if count==l:
                 num+=l
         return  num
a= Solution()
words = ["cat","bt","hat","tree"]
chars = "atach"
print(a.countCharacters(words,chars))
posted @ 2020-03-17 11:22  rmxob  阅读(179)  评论(0)    收藏  举报