見證Python中else新用法

今天刷leetcode題的時候看到了else新用法
應該也不算新用法,只是以前沒見過
即else是與for對應,而非if

題目描述1160.拼寫單詞

給你一份『詞彙表』(字符串數組) words 和一張『字母表』(字符串) chars。

假如你可以用 chars 中的『字母』(字符)拼寫出 words 中的某個『單詞』(字符串),那麼我們就認爲你掌握了這個單詞。

注意:每次拼寫時,chars 中的每個字母都只能用一次。

返回詞彙表 words 中你掌握的所有單詞的 長度之和。

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/find-words-that-can-be-formed-by-characters
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。

import collections
class Solution:
    def countCharacters(self, words: List[str], chars: str) -> int:
        char_cnt = collections.Counter(chars)
        ans = 0
        for word in words:
            word_cnt = collections.Counter(word)
            for c in word:
                if char_cnt[c] < word_cnt[c]:
                    break
            else:
                ans += len(word)
        return ans

其中else操作與for漁業局對應

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章