1. 程式人生 > 其它 >leetcode 1160. Find Words That Can Be Formed by Characters(python)

leetcode 1160. Find Words That Can Be Formed by Characters(python)

技術標籤:leetcodeleetcode

描述

You are given an array of strings words and a string chars.

A string is good if it can be formed by characters from chars (each character can only be used once).

Return the sum of lengths of all good strings in words.

Example 1:

Input: words = ["cat","bt","hat","tree"], chars = "atach"
Output: 6
Explanation: 
The strings that can be formed are "cat" and "hat" so the answer is 3 + 3 = 6.	

Example 2:

Input: words = ["hello","world","leetcode"], chars = "welldonehoneyr"
Output: 10
Explanation: 
The strings that can be formed are "hello" and "world" so the answer is 5 + 5 = 10.

Note:

  • 1 <= words.length <= 1000
  • 1 <= words[i].length, chars.length <= 100
  • All strings contain lowercase English letters only.

解析

根據題意,只要找出 words 中的 good 字串然後將它們的長度相加即可。遍歷 words 中的每個單詞,然後遍歷每個單詞 word 的每個字元 c ,如果該字元 c 在 word 中出現的次數超過在 char 中的出現次數,則跳過該單詞,直接去判斷下一個單詞;如果該單詞是 good 的,則將長度追加到 res 中,繼續進行下一個單詞的判斷,遍歷結束即可得到答案

解答

class Solution(object):
def countCharacters(self, words, chars):
    """
    :type words: List[str]
    :type chars: str
    :rtype: int
    """
    res = 0
    for word in words:
        boolean = True
        for c in word:
            if word.count(c) > chars.count(c):
                boolean = False
                break
        if boolean:
            res += len(word)
    return res

執行結果

Runtime: 72 ms, faster than 94.16% of Python online submissions for Find Words That Can Be Formed by Characters.
Memory Usage: 14.3 MB, less than 29.18% of Python online submissions for Find Words That Can Be Formed by Characters.

原題連結:https://leetcode.com/problems/find-words-that-can-be-formed-by-characters/