[LeetCode] 211. Design Add and Search Words Data Structure, Medium

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

1. 문제

  • 요구 사항에 맞는 WordDictionary class를 구현하라.

2. 해결

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

    addWord(word: string): void {
        let node = this.root;
        
        for(const char of word) {
            if(!node.children.has(char)) {
                node.children.set(char, new TrieNode());
            }
            
            node = node.children.get(char);
        }

        node.isEnd = true;
    }

    search(word: string): boolean {
        const DFS = (node: TrieNode, i:number) => {
            if(i === word.length) return node.isEnd;
           
            const char = word[i];
           
            if(char ==='.') {
                for(const child of node.children.values()) {
                    if(DFS(child, i + 1)) return true;
                }    
                return false;
            } else {
                if(!node.children.has(char)) return false;
                return DFS(node.children.get(char), i + 1)
            }
        }
       
        return DFS(this.root,0)
    }
}

/**
 * Your WordDictionary object will be instantiated and called as such:
 * var obj = new WordDictionary()
 * obj.addWord(word)
 * var param_2 = obj.search(word)
 */
  • Trie로 문자열을 구성하고, 처리하면 된다.
  • search 쪽에서 . 에 대한 처리가 막혔다.
  • 존재하는 모든 자식에 대해 동일한 로직 처리를 해줘야 하므로 재귀 함수로 구현.
저작자표시 (새창열림)
'CodingTest/LeetCode' 카테고리의 다른 글
  • [LeetCode] 98. Validate Binary Search Tree, Medium
  • [LeetCode] 212. Word Search II, Hard
  • [LeetCode] 648. Replace Words, Medium
  • [LeetCode] 677. Map Sum Pairs, 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)
  • 블로그 메뉴

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

  • 공지사항

  • 인기 글

  • 태그

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

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
뜸부깅
[LeetCode] 211. Design Add and Search Words Data Structure, Medium
상단으로

티스토리툴바