코딩 공부/Leetcode

[Python] 916. Word Subsets

일하는 공학도 2025. 1. 10. 15:14
728x90

난이도 : Medium

words2의 하위 리스트에 있는 알파벳들이 포함됐는지 확인하고, words2의 모든 요소들이 포함된 words1의 단어들만 return하는 경우이다.

 

맨 처음엔 생각보다 쉬운데? 싶어서 간단하게 썼다.

class Solution(object):
    def wordSubsets(self, words1, words2):
        """
        :type words1: List[str]
        :type words2: List[str]
        :rtype: List[str]
        """
        words2_n = [char for word in words2 for char in word]
        res = []
        a = len(words2_n)

        for word in words1:
            b = 0
            words1_n = list(word)
            for i in range(a):
                if words2_n[i] in words1_n:
                    words1_n.remove(words2_n[i])
                    b += 1
                if a == b:
                    res.append(word)
        return res
  1. words2의 요소를 모두 조각내서 하나의 리스트(words2_n)로 제작
  2. for 문으로 words1도 리스트로 조각내고(words1_n)
  3. 내부 for문으로 words2_n의 요소가 words1_n에 있으면, words1_n에서 해당 요소를 지우기
  4. 지울때마다 b를 1씩 더하고, words2_n의 길이와 같을 때, res 리스트 뒤에 word를 추가

이 결과는, 다음에서 막혔다.

words1 = ["amazon","apple","facebook","google","leetcode"]

words2 = ["lo","eo"]

Output = ["google"]

원래는 ["google","leetcode"]가 나와야 한다.... 중복되면 삭제한 것이 문제인듯 하였다.

 

class Solution(object):
    def wordSubsets(self, words1, words2):
        """
        :type words1: List[str]
        :type words2: List[str]
        :rtype: List[str]
        """
        count = collections.Counter()
        for b in words2:
            count = count | collections.Counter(b)
            
        return [a for a in words1 if collections.Counter(a) & count == count]
  1. collections.Counter()로 변수 초기화
  2. |(or) 연산자를 사용하여, count에 words2의 알파벳을 하나씩 저장한다
  3. return에는, collections.Counter(a)로 words1의 알파벳 확인
  4. collections.Counter(a)와 count를 &(and) 연산자로, 합집합을 구함
  5. 4에 있는 합집합과 count와 동일한지 확인한 words1의 요소만 추출

위의 해답은, 해결할 방법을 찾다가 발견한 획기적인 방법이라 생각하였다.

출처 : https://walkccc.me/LeetCode/problems/916/

728x90