ð 211. æ·»å äžæ玢åè¯ - æ°æ®ç»æ讟计
2022幎10æ10æ¥
- algorithm
ð 211. æ·»å äžæ玢åè¯ - æ°æ®ç»æ讟计
éŸåºŠ: ð
é®é¢æè¿°
解æ³
class WordDictionary {
// æè·¯ïŒ
// æé 26 åæ ïŒå¯¹äºå
å« . çåè¯ïŒæ¥è¯¢ææåšé空åæ
Node root;
public WordDictionary() {
this.root = new Node('a'); // èæ倎ç»ç¹
}
public void addWord(String word) {
Node cur = root;
int len = word.length();
for(int i = 0; i < len; i ++) {
char c = word.charAt(i);
int index = c - 'a';
if(cur.child[index] == null) {
cur.child[index] = new Node(c);
}
cur = cur.child[index];
}
cur.end = true; // æ è®°ç»æ¢
}
public boolean search(String word) {
Node cur = root;
int len = word.length();
return searchAtIndex(word, len, 0, cur);
}
private boolean searchAtIndex(String word, int len, int index, Node cur) {
// éåœç»æ¢æ¡ä»¶
if(index == len) {
return false; // äžé¢çé»èŸå€æïŒä¿è¯äºæ ¹æ¬äžå¯èœå°èŸŸè¿é
}
//
char c = word.charAt(index);
if(c != '.') {
int i = c - 'a';
if(cur.child[i] == null) {
return false;
}
if(index == len - 1) {
return cur.child[i].end; // 诎ææ¯æåäžäžªå笊ïŒå€ææ¯åŠæ¯æ«å°Ÿèç¹
} else {
return searchAtIndex(word, len, index + 1, cur.child[i]);
}
} else {
// 诎ææ¯ . å¯ä»¥å¹é
ä»»äœå笊ïŒæ¥æŸé空åèç¹
for(int i = 0; i < 26; i ++) {
if(cur.child[i] != null) {
if(index == len - 1) {
// æåäžäžªå笊ïŒåªéèŠå€æåèç¹æ¯åŠæ¯ç»æ¢ç¹å³å¯
if(cur.child[i].end) {
return true;
}
} else {
if(searchAtIndex(word, len, index + 1, cur.child[i])) {
return true;
}
}
}
}
return false;
}
}
}
class Node {
char val;
boolean end;
Node[] child;
public Node(char val) {
this.val = val;
this.end = false;
this.child = new Node[26];
}
}
/**
* Your WordDictionary object will be instantiated and called as such:
* WordDictionary obj = new WordDictionary();
* obj.addWord(word);
* boolean param_2 = obj.search(word);
*/