래원

[LeetCode] 1408. String Matching in an Array (Python) 본문

알고리즘/LeetCode

[LeetCode] 1408. String Matching in an Array (Python)

Laewon Jeong 2025. 1. 7. 14:44

 

난이도: Easy

 

문제 설명


Given an array of string words, return all strings in words that is a substring of another word

You can return the answer in any order.

substring is a contiguous sequence of characters within a string

 

문제 예제


Example 1:

Input: words = ["mass","as","hero","superhero"]
Output: ["as","hero"]
Explanation: "as" is substring of "mass" and "hero" is substring of "superhero".
["hero","as"] is also a valid answer.

 

Example 2:

Input: words = ["leetcode","et","code"]
Output: ["et","code"]
Explanation: "et", "code" are substring of "leetcode".

 

Example 3:

Input: words = ["blue","green","bu"]
Output: []
Explanation: No string of words is substring of another string.

 

제한 사항


  • 1 <= words.length <= 100
  • 1 <= words[i].length <= 30
  • words[i] contains only lowercase English letters.
  • All the strings of words are unique.

 

Solution(솔루션)

class Solution:
    def stringMatching(self, words: List[str]) -> List[str]:
        n = len(words)
        answer = []

        for i in range(n):
            for j in range(n):
                if i != j and words[i] in words[j]:
                    answer.append(words[i])
                    break
        
        return answer

 

제한사항을 보니 오히려 Brute Force 방식으로 푸는게 제일 효율적일 것 같아서 이 방식으로 코드를 작성했다.

 

2중 for문을 돌려 words[i]가 words[j]에 있다면 answer에 words[i]를 추가하고 마지막에 answer를 return 하였다.

 


문제: 1408. String Matching in an Array

 

깃허브: github

 

algorithm_practice/LeetCode/1524-string-matching-in-an-array at main · laewonJeong/algorithm_practice

하루 한 문제 챌린지. Contribute to laewonJeong/algorithm_practice development by creating an account on GitHub.

github.com