[LeetCode] 648. Replace Words, Medium

2025. 4. 9. 17:12·CodingTest/LeetCode
반응형

1. 문제

  • 어간으로 구성된 dictionary와 파생어로 구성된 sentence 문자열이 주어질 때, 파생어 요소 중 어간이 있는 요소는 어간으로 교체하여 반환하라.

2. 해결

class TrieNode {
    children:Map<string, TrieNode>;
    root:string;
    constructor() {
        this.children = new Map();
        this.root = '';
    }
}

class Trie{
    root:TrieNode;
    constructor() {
        this.root = new TrieNode();
    }

    insert(word:string) {
        let node = this.root;

        let root = '';
        for(const char of word) {
            if(!node.children.has(char)){
                node.children.set(char, new TrieNode());
            }

            node = node.children.get(char);
            root += char;
        }

        node.root = root;
    }

    findRoot(word: string): string {
        let node = this.root;

        for (const char of word) {
            if (!node.children.has(char)) {
                return ''; 
            }

            node = node.children.get(char)!;

            if (node.root) {
                return node.root; 
            }
        }

        return ''; 
    }

}

function replaceWords(dictionary: string[], sentence: string): string {
    const trie = new Trie();
    for(const word of dictionary) {
        trie.insert(word);
    }

    const sentenceArr = sentence.split(' ');

    for(let i = 0; i<sentenceArr.length; i++) {
        const root = trie.findRoot(sentenceArr[i]);
        if(root) {
            sentenceArr[i] = root;
        }
    }

    return sentenceArr.join(' ')
};
  • 어간으로 구성된 트라이를 만들고, 해당 트라이에서 어간을 발견하면 바로 리턴하여 해당 값으로 교체해준다.
저작자표시 (새창열림)
'CodingTest/LeetCode' 카테고리의 다른 글
  • [LeetCode] 212. Word Search II, Hard
  • [LeetCode] 211. Design Add and Search Words Data Structure, Medium
  • [LeetCode] 677. Map Sum Pairs, Medium
  • [LeetCode] 208. Implement Trie (Prefix Tree), Medium
뜸부깅
뜸부깅
코딩에 대한 여러 개인적인 생각을 정리하고 공부를 하는 공간입니다!!
  • 뜸부깅
    코오오딩
    뜸부깅
  • 전체
    오늘
    어제
    • Note (429)
      • Skill (31)
        • Java & Spring (9)
        • Javascript & HTML & CSS (0)
        • React (0)
        • Next.js (22)
      • CodingTest (389)
        • 백준 온라인 저지(BOJ) (140)
        • 프로그래머스(Programmers) (79)
        • LeetCode (170)
      • Algorithm & Data Structure (6)
      • [Project] 포트폴리오 (3)
        • Front end (3)
        • Back end (0)
  • 블로그 메뉴

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

  • 공지사항

  • 인기 글

  • 태그

    boj1427
    백준2751
    프로그래머스
    Java
    component-scan
    TypeScript
    next 14
    boj2108
    백준1260
    백준7576
    BOJ
    백준1427
    자바
    백준7576자바
    leetcode 2236
    medium
    Easy
    meidum
    알고리즘
    백준
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
뜸부깅
[LeetCode] 648. Replace Words, Medium
상단으로

티스토리툴바