916. Word Subsets

2025. 1. 12. 15:24·Algorithm/Leetcode

https://leetcode.com/problems/word-subsets/description/?envType=daily-question&envId=2025-01-10

 

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 = ["lc","eo"]Output: ["leetcode"]

Example 3:
Input: words1 = ["acaac","cccbb","aacbb","caacc","bcbbb"], words2 = ["c","cc","b"]Output: ["cccbb"]

 

 

words1을 순회하면서, 각 문자열이 words2의 부분집합으로 만들 수 있는지 검사하는 문제였다.

 

내가 접근한 방식은 다음과 같다.

  1. words2를 순회하면서 각 문자의 등장횟수를 모두 더해준다.
  2. words1를 순회하면서 각 등장횟수를 저장한다.
  3. words2를 저장한 해쉬맵의 키를 돌면서, containsKey 여부와 등장횟수를 체크한다.
  4. 만약에 containsKey와 words1의 등장횟수가 많은 경우에만 결과값에 넣어준다.

 

예제는 다 통과했지만, 해당 예제에서 통과하지 못했다.

words1 =["amazon","apple","facebook","google","leetcode"]words2 =["lo","eo"]

Use Testcase
Output["google"]
Expected["google","leetcode"]

 

word2 Map

l: 1, e: 1, o:2

 

word1 Map (Leetcode)

l: 1, e:3, o: 1

 

나의 로직 상으로 word1의 o 등장횟수가 더 적기때문에 leetcode 단어가 결과값에 포함하면 안됐지만, 그 차이때문에 틀렸다. 

 

현재 나의 코드는 

words2 = ["lo", "eo"]일때 모든 문자를 합산하기 때문인데,

l:1, o:1, e:1 처럼 최대 등장횟수를 계산해야한다. 

 

따라서, 2개의 Map을 선언하여 max값에 해당하는 등장횟수만 저장하도록 구현해서 통과했다.

 

정답 코드

class Solution {
    public List<String> wordSubsets(String[] words1, String[] words2) {
        List<String> res = new ArrayList<>();

        int [] maxFreq = new int[26];
        for(String word : words2) {
            int [] freq = new int[26];
            for(char c : word.toCharArray()) {
                freq[c - 'a']++;
            }

            for(int i = 0; i < 26; i++) {
                maxFreq[i] = Math.max(maxFreq[i], freq[i]);
            }
        }

        for(String word : words1) {
            int [] wordFreq = new int[26];
            for(char c : word.toCharArray()) {
                wordFreq[c - 'a']++;
            }

            boolean flag = true;
            for(int i = 0; i < 26; i++) {
                if (wordFreq[i] < maxFreq[i]) {
                    flag = false;
                    break;
                }
            }

            if (flag) {
                res.add(word);
            }
        }
        return res;
    }
}

 

 

맵을 사용하는 것보다 배열을 사용하는 것이 시간복잡도 측면에서나 코드 가독성에서나 훨씬 뛰어났다.

 

 

'Algorithm > Leetcode' 카테고리의 다른 글

934. Shortest Bridge  (0) 2025.01.15
3223. Minimum Length of String After Operations  (0) 2025.01.13
542. 01 Matrix  (0) 2025.01.07
78. Subsets  (0) 2025.01.07
494. Target Sum  (2) 2025.01.06
'Algorithm/Leetcode' 카테고리의 다른 글
  • 934. Shortest Bridge
  • 3223. Minimum Length of String After Operations
  • 542. 01 Matrix
  • 78. Subsets
미네구스
미네구스
  • 미네구스
    망구스 blog
    미네구스
  • 전체
    오늘
    어제
    • 분류 전체보기 (175)
      • Kotlin (0)
      • 시큐리티 (0)
        • 개발자 유미 (0)
      • 배포 (4)
      • 회고 (0)
      • Algorithm (143)
        • 프로그래머스 코딩테스트 문제풀이전략 (37)
        • 백준 (66)
        • 프로그래머스 (18)
        • Leetcode (22)
        • 코테 팁 (0)
      • 프로젝트 (8)
        • WEPIK (3)
        • PICK-O (5)
      • CS (1)
        • 운영체제 (5)
        • 네트워크 (1)
        • 면접스터디 (2)
      • 면접 (1)
        • 코테후기 (0)
        • 면접후기 (1)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    N과 M
    백트래킹
    `
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.2
미네구스
916. Word Subsets
상단으로

티스토리툴바