---
# System prepended metadata

title: Untitled

---

用"#"表示末端 不過這前提是要dict word本身沒有包含特殊字元

注意22行

```javascript=
/**
 * @param {string[]} dictionary
 * @param {string} sentence
 * @return {string}
 */

var replaceWords = function(dictionary, sentence) {
    const trieRoot = {};

    // build trie
    const insertWord = (word) => {
        let cur = trieRoot;
        for (var i of word) {
            if (!cur[i]) {
                cur[i] = {};
            }
            cur = cur[i];
            if (cur['#']) {
                return;
            }
        }
        // save whole word
        cur['#'] = word;
    }
    dictionary.forEach(insertWord);
    
    // mapping word
    const mapWord = (s) => {
        let cur = trieRoot;
        for (var i of s) {
            if (!cur[i]) return s;
            
            cur = cur[i];
            
            // 爽爽return
            if (cur['#']) return cur['#'];
        }
        return s;
    }
    return sentence.split(' ').map(mapWord).join(' ');
};
                
```

注意22行
和34行
```javascript=
/**
 * @param {string[]} dictionary
 * @param {string} sentence
 * @return {string}
 */

var replaceWords2 = function(dictionary, sentence) {
    const trieRoot = {};

    // build trie
    const insertWord = (word) => {
        let cur = trieRoot;
        for (var i of word) {
            if (!cur[i]) {
                cur[i] = {};
            }
            cur = cur[i];
            if (cur['#']) {
                return;
            }
        }
        // save boolean
        cur['#'] = true;
    }
    dictionary.forEach(insertWord);
    
    // mapping word
    const mapWord = (s) => {
        let cur = trieRoot;
        let tmp = ''
        for (var i of s) {
            if (!cur[i]) return s;
            
            // 就要一個個加
            tmp += i;
            cur = cur[i];
            
            if (cur['#']) return tmp;
        }
        return s;
    }
    return sentence.split(' ').map(mapWord).join(' ');
};
```
