파비의 매일매일 공부기록

2023.12.05 Today's Challenge 본문

Problem Solving/LeetCode

2023.12.05 Today's Challenge

fabichoi 2023. 12. 5. 23:45

https://leetcode.com/problems/find-words-that-can-be-formed-by-characters/?envType=daily-question&envId=2023-12-02

 

Find Words That Can Be Formed by Characters - LeetCode

Can you solve this real interview question? Find Words That Can Be Formed by Characters - 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). Retu

leetcode.com

해쉬맵 형태로 푸는 법 말고
좀 더 쉬운 방법은 없을까..

class Solution:
    def countCharacters(self, words: List[str], chars: str) -> int:
        cnt = [0] * 26
        for c in chars:
            cnt[ord(c) - ord('a')] += 1
        
        ans = 0
        for word in words:
            word_cnt = [0] * 26
            for c in word:
                word_cnt[ord(c) - ord('a')] += 1
            is_ok = True
            for i in range(26):
                if cnt[i] < word_cnt[i]:
                    is_ok = False
                    break
            if is_ok:
                ans += len(word)
        return ans
반응형

'Problem Solving > LeetCode' 카테고리의 다른 글

2023.12.07 Today's Challenge  (0) 2023.12.07
2023.12.06 Today's Challenge  (0) 2023.12.06
2023.12.04 Today's Challenge  (1) 2023.12.04
2023.12.03 Today's Challenge  (0) 2023.12.03
2023.12.02 Today's Challenge  (1) 2023.12.02
Comments