saurus2
Saurus2
saurus2
전체 방문자
오늘
어제
  • 분류 전체보기
    • 개발
      • AJAX
    • ML Ops
    • Profile
    • 음식점
    • 배낭여행
    • 컴퓨터공학
      • 알고리즘 공부
      • C++
      • Sever 스터디
      • Java spring
      • 알고리즘 _ 문제해결
      • 딥러닝
      • Java 정리
      • Python
      • LeetCode 1000
      • Machine Learning Study
      • Sign language Detection Pro..
      • LeetCode Solutions
    • 비콘
    • 데일리 리포트
    • 유학일기
      • 영어 공부
      • Daily
    • AI Master Degree
      • Data Mining
      • AI and Data engineering
      • Math Foundations for Decisi..
      • Natural Language Processing

블로그 메뉴

  • 홈
  • 태그
  • 미디어로그
  • 위치로그
  • 방명록

공지사항

인기 글

태그

  • 딥러닝
  • c++
  • 릿코드
  • 문제해결능력
  • 개발자 취업준비
  • 온라인저지
  • LeetCode
  • 리트코드
  • 알고리즘
  • Python
  • 개발자
  • two pointer
  • 취준
  • 알고리즘문제해결
  • 파이썬
  • 백준
  • 취업준비
  • 딕셔너리
  • DFS
  • BFS

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
saurus2

Saurus2

컴퓨터공학/LeetCode 1000

[LeetCode] 916. Word Subsets

2022. 7. 30. 19:52

916. Word Subsets

Medium
 

You are given two string arrays words1 and words2.

A string b is a subset of string a if every letter in b occurs in a including multiplicity.

  • For example, "wrr" is a subset of "warrior" but is not a subset of "world".

A string a from words1 is universal if for every string b in words2, b is a subset of a.

Return an array of all the universal strings in words1. You may return the answer in any order.

 

Example 1:

Input: words1 = ["amazon","apple","facebook","google","leetcode"], words2 = ["e","o"]
Output: ["facebook","google","leetcode"]

Example 2:

Input: words1 = ["amazon","apple","facebook","google","leetcode"], words2 = ["l","e"]
Output: ["apple","google","leetcode"]

 

Constraints:

  • 1 <= words1.length, words2.length <= 104
  • 1 <= words1[i].length, words2[i].length <= 10
  • words1[i] and words2[i] consist only of lowercase English letters.
  • All the strings of words1 are unique.

 


문제 해설

문제 접근

  1. 단어 세트 두개가 주어진다.
  2. 두번째 단어 (두번째 단어 세트)에 들어있는 모든 문자가 하나의 단어(첫번째 단어 세트) 안에 포함이 되어있는 Subset 이라면 답으로 반환
  3. 모든 단어는 길이가 1부터 10^4 까지 이다.
  4. 두번째 단어를 모두세고 첫번째 단어를 모두 샌다면 N^2 이 되고, 각 단어들을 확인하려면 N^3 이 된다.
  5. N^3 은 시간 초과가 될것이다.
  6. 모든 단어를 각각 확인하지 않고 다른 방법이 필요하다.

문제 풀이

  1. 딕셔너리(해쉬맵) 에 한꺼번에 처리할 수 있는 값을 담아야한다.
  2. 첫번째 단어가 두번째 단어 세트의 모든 단어가 들어있는지 확인해야한다. 
  3. 예를들어, 첫번째 단어가 "abcdd" 이고 두번째 단어들이 "abdd", "aabdd" 라면, 성립되지 않는다.
  4. "aabdd" 에서 a가 두개이기 때문에 첫번째 단어와 조건이 성립되지 않는다. 
  5. 딕셔너리를 두번째 단어 세트의 알파벳 갯수로 만들되, 최대값만 가지고 있으면 한번의 처리로 끝낼 수 있다.
  6. 예제로 구상한다면, {a : 2, b : 1, d : 2} 가 된다, a 최대 갯수 계산시 답을 걸러낼 수 있다. 

소스코드 

class Solution:
    def wordSubsets(self, words1: List[str], words2: List[str]) -> List[str]:
        def count(word):
            hashmap = defaultdict(int)
            for latter in word:
                hashmap[latter] += 1
            return hashmap
        hashmap2 = defaultdict(int)
        for word in words2:
            for k, v in count(word).items():
                hashmap2[k] = max(hashmap2[k], v)
        ans = []
        for word in words1:
            hashmap3 = count(word)
            flag = True
            for k, v in hashmap2.items():
                if hashmap3[k] < hashmap2[k]:
                    flag = False
            if flag:
                ans.append(word)
        return ans

'컴퓨터공학 > LeetCode 1000' 카테고리의 다른 글

[LeetCode] 108. Convert Sorted Array to Binary Search Tree  (0) 2022.08.10
[LeetCode] 621. Task Scheduler  (0) 2022.07.30
[LeetCode] 251. Flatten 2D Vector  (0) 2022.07.29
[LeetCode] 890. Find and Replace Pattern  (0) 2022.07.29
물건 사고 파는 문제 파이썬 order, sell, return  (0) 2022.03.07
    '컴퓨터공학/LeetCode 1000' 카테고리의 다른 글
    • [LeetCode] 108. Convert Sorted Array to Binary Search Tree
    • [LeetCode] 621. Task Scheduler
    • [LeetCode] 251. Flatten 2D Vector
    • [LeetCode] 890. Find and Replace Pattern
    saurus2
    saurus2
    Simple is Best

    티스토리툴바