745. Prefix and Suffix Search

use Trie

็ต„ๅˆ็š„ๆ™‚ๅ€™: public WordFilter(String[] words)

ๅ‰้ขๆ”พๅŽŸๅ–ฎ่ฉž็š„้ƒจๅˆ†, ๅพŒ้ข้ƒฝๆ”พๅฎŒๆ•ด็š„, ็‚บไป€้บผ้€™ๆจฃๅšๅ‘ข๏ผŸ

apple#apple, 'pple#apple', 'ple#apple', 'le#apple', 'e#apple', #apple',

ๆ‰€ไปฅ f() ๆฏ”ๅฐๆ™‚, input ๅฆ‚ๆžœๆ˜ฏ le#ap (suffix + # + prefix

้€™ๆจฃๅพžๅ‰้ข้–‹ๅง‹ๆฏ”ๅฐ, ๅฐฑๆœƒๅฏไปฅๆฏ”ๅฐๅˆฐ 'le#apple'

ๅ› ็‚บ็ต„็š„ๆ™‚ๅ€™, ๅฐฑๆœƒ่ฎŠๆˆ sufixๅ’Œ # ๅŽŸๅ–ฎ่ฉž ็š„ๆ‰€ๆœ‰็ต„ๅˆ๏ผ๏ผ๏ผ

T:

WordFilter : O(n*L^2), n is words size, L is each word's len

f:() : O(QL), Q is times of query

S: O(n*L^2)

class WordFilter {
    
    class TrieNode {
        Map<Character, TrieNode> sons;
        int weight;
        TrieNode() {
            this.sons = new HashMap<>();
            this.weight = weight;
        }
    }
    private TrieNode root;
    private void insert(String word, int weight) {
        TrieNode node = root;
        for (char c : word.toCharArray()) {
            node.sons.putIfAbsent(c, new TrieNode());
            node = node.sons.get(c);
            node.weight = weight;
        }
    }

    public WordFilter(String[] words) {
        root = new TrieNode();
        for (int i = 0; i < words.length; i++) {
            int weight = i;
            
            String word = "{" + words[i];
            insert(word, weight);
            for (int j = 0; j < word.length(); j++) {
                insert(word.substring(j+1) + word, weight);
            }
        }
    }
    
    public int f(String prefix, String suffix) {
        TrieNode node = root;
        for (char c : (suffix + "{" + prefix).toCharArray()) {
            if (node.sons.get(c) == null) {
                return -1;
            } 
            node = node.sons.get(c);
        }
        return node.weight;
    }
}

/**
 * Your WordFilter object will be instantiated and called as such:
 * WordFilter obj = new WordFilter(words);
 * int param_1 = obj.f(prefix,suffix);
 */

use HashMap

https://leetcode.com/problems/prefix-and-suffix-search/discuss/110044/Three-ways-to-solve-this-problem-in-Javaarrow-up-right

ไนŸๅฏไปฅ็”จ hashmap, ไฝ†่จ˜ๆ†ถ้ซ”ๆ‡‰่ฉฒๆถˆ่€—ๅพˆๅ…‡, ไฝ† f() ้žๅธธๅฟซ๏ผšO(1) or O(L), ไฝ†ๅœจ ๅญ—ไธฒ่ถ…้•ทๆ™‚, ๆ‡‰่ฉฒๆœƒ hash conflic ๅคชๅšด้‡่€Œ็„กๆณ•ไฝœ็”จ...

Last updated