본문 바로가기
프로그래밍/알고리즘

[LeetCode] 648. Replace Words

by 제이제이_은재 2024. 6. 7.
반응형

 

 

 

❓Problem

In English, we have a concept called root, which can be followed by some other word to form another longer word - let's call this word derivative. For example, when the root "help" is followed by the word "ful", we can form a derivative "helpful".

Given a dictionary consisting of many roots and a sentence consisting of words separated by spaces, replace all the derivatives in the sentence with the root forming it. If a derivative can be replaced by more than one root, replace it with the root that has the shortest length.

Return the sentence after the replacement.

 

Example 1:

Input: dictionary = ["cat","bat","rat"], sentence = "the cattle was rattled by the battery"
Output: "the cat was rat by the bat"
Example 2:

Input: dictionary = ["a","b","c"], sentence = "aadsfasf absbs bbab cadsfafs"
Output: "a a b c"
 

Constraints:

1 <= dictionary.length <= 1000
1 <= dictionary[i].length <= 100
dictionary[i] consists of only lower-case letters.
1 <= sentence.length <= 106
sentence consists of only lower-case letters and spaces.
The number of words in sentence is in the range [1, 1000]
The length of each word in sentence is in the range [1, 1000]
Every two consecutive words in sentence will be separated by exactly one space.
sentence does not have leading or trailing spaces.

 

 

🗝️  [내가 푼] Answer1

/**
 * @param {string[]} dictionary
 * @param {string} sentence
 * @return {string}
 */
var replaceWords = function(dictionary, sentence) {
    dictionary.sort(); 
    
    const splitedSentence = sentence.split(" ");
    
    const resultArray = splitedSentence.map(word => {
        for (const root of dictionary) {
            if (word.startsWith(root)) {
                return root;
            }
        }
        return word;
    });

    return resultArray.join(' ');
};

 

 

🎈Review

1. sort() 를 사용해 짧은 게 가장 앞에 나오도록 정렬.

2. startsWith 메서드를 사용하여 문자열이 특정 접두사로 시작하는 지 확인 후 맞다면 대체 단어를 리턴

3. 그렇지 않다면 원래 문자열 리턴

반응형

'프로그래밍 > 알고리즘' 카테고리의 다른 글

[LeetCode] 268. Missing Number  (0) 2024.05.23
[LeetCode] 3152. Special Array II  (0) 2024.05.23
[LeetCode] 3151. Special Array I  (0) 2024.05.23

댓글