coding test/leetCode
[leetCode/JS]1408. String Matching in an Array
쭘봉
2025. 1. 7. 10:57
난이도 [ 😊 ] 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.
A 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:
Example 3: In put: words = ["blue","green","bu"]
Output: [] Explanation: No string of words is substring of another -string.
Constraints
1 <= words.length <= 100
1 <= words[i].length <= 30
words[i]
contains only lowercase English letters.- All the strings of
words
are unique.
내 솔루션
var stringMatching = function(words) {
// 길이 순으로 정렬해서 뒤쪽에 필요없는 비교를 줄임.
words.sort((a, b) => a.length - b.length);
const returnVal = new Set();
// 정렬했기 때문에 i는 항상 j보다 항상 짧은 단어
for(let i = 0; i < words.length; i++) {
for(let j = i + 1; j < words.length; j++) {
if(words[i] === words[j]) continue;
if(words[j].includes(words[i])) {
returnVal.add(words[i]);
break;
}
}
}
return [...returnVal];
};
감상평
- 25년 첫 리트코드로써 딱 좋은 난이도의 문제였다.