leetcode 1160. Find Words That Can Be Formed by Characters spell words
leetcode 2020 March 1 question daily punch
Title:
give you a "Glossary" (array of strings) words and an "alphabet" (string) chars. If you can spell out words in a "word" (string) with the chars in the "letter" (character), then we think you've mastered the word. Note: Each time the spelling, chars each letter can only be used once. Return vocabulary words in all the words you have mastered the sum of the lengths.
Example 1:
Input: words = [ "cat", "bt", "hat", "tree"], chars = "atach"
Output: 6
Explanation: string may be formed "cat" and "hat", so the answer is 3 + 3 = 6.
Example 2:
Input: words = [ "hello", "world", "leetcode"], chars = "welldonehoneyr"
Output: 10
Explanation: may form a string "hello" and "world", so the answer is 5 + 5 = 10.
Tip:
. 1 <= words.length <= 1000
. 1 <= words [I] .length, chars.length <= 100
all the strings are included only lowercase letters
Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/find-words-that-can-be-formed-by-characters
Ideas: Python
detail:
- str convert list: list1 = list (str1).
- list转str: “”.join(list)
- To delete an element in the list
list1=[1,2,3,3,4,5]
list1.remove(3)
print(list1)
# 输出[1,2,3,4,5]
Code:
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
This blog is an original work, welcomed the guidance, reproduced, please indicate the source, attach a link to this article, thank you!