본문 바로가기

Algorithm

[leetcode] 211. Design Add and Search Words Data Structure

Design a data structure that supports adding new words and finding if a string matches any previously added string.

Implement the WordDictionary class:

  • WordDictionary() Initializes the object.
  • void addWord(word) Adds word to the data structure, it can be matched later.
  • bool search(word) Returns true if there is any string in the data structure that matches word or false otherwise. word may contain dots '.' where dots can be matched with any letter.

Example:

Input ["WordDictionary","addWord","addWord","addWord","search","search","search","search"]

[[],["bad"],["dad"],["mad"],["pad"],["bad"],[".ad"],["b.."]]

Output [null,null,null,null,false,true,true,true]

Explanation WordDictionary wordDictionary = new WordDictionary();

wordDictionary.addWord("bad");

wordDictionary.addWord("dad");

wordDictionary.addWord("mad");

wordDictionary.search("pad"); // return False

wordDictionary.search("bad"); // return True

wordDictionary.search(".ad"); // return True

wordDictionary.search("b.."); // return True

 

 

Constraints:

  • 1 <= word.length <= 500
  • word in addWord consists lower-case English letters.
  • word in search consist of '.' or lower-case English letters.
  • At most 50000 calls will be made to addWord and search.

 

트라이를 이용해서 풀었다. 전통적인 트라이와의 차이점은 wildcard 처리를 했다는 점이다.

검색을 하다가 와일드 카드를 만난다면 이후 단어부터 다시 검색을 시작한다.

(맨 마지막 단어는 for loop 를 타지 않고 마지막의 cur.endOfWord 만을 체크한다.)

 

class WordDictionary {
	Node root = new Node();

	public void addWord(String word) {
		Node cur = this.root;

		for (int i = 0; i < word.length(); i++) {
			int idx = word.charAt(i) - 'a';

			if (cur.children[idx] == null) {
				cur.children[idx] = new Node();
			}

			if (i == word.length() - 1) {
				cur.children[idx].endOfWord = true;
			}

			cur = cur.children[idx];
		}
	}

	public boolean search(String word) {
		return solve(word, this.root);
	}

	private boolean solve(String word, Node node) {
		Node cur = node;

		for (int i = 0; i < word.length(); i++) {
			int idx = word.charAt(i) - 'a';

			if (idx == -51) {
				for (int j = 0; j < cur.children.length; j++) {
					if (cur.children[j] != null && solve(word.substring(i+1), cur.children[j])) {
						return true;
					}
				}

				return false;
			}

			Node next = cur.children[idx];

			if (next == null) {
				return false;
			}

			cur = next;
		}

		return cur.endOfWord;
	}

	static class Node {
		Node [] children = new Node[26];
		boolean endOfWord;
	}
}