😎풀이

  1. sentence를 공백을 기준으로 각 문자 분리
  2. 짧은 순서대로 우선 치환되어야 하므로 dictionary를 길이 기준 오름차 순 정렬
  3. 각 문자를 순회하며 가장 짧은 접두사로 치환
  4. 문자를 공백을 기준으로 병합하여 문자열 반환
function replaceWords(dictionary: string[], sentence: string): string {
    const words = sentence.split(" ")
    const sortedDicts = dictionary.toSorted((a, b) => a.length - b.length)
    const replaced = words.map(word => {
        for(const dict of sortedDicts) {
            if(word.startsWith(dict)) return dict
        }
        return word
    })
    return replaced.join(' ')
};
profile
내 지식을 공유할 수 있는 대담함

0개의 댓글