Prefix and Suffix Search

题目
Given many words, words[i] has weight i.

Design a class WordFilter that supports one function, WordFilter.f(String prefix, String suffix). It will return the word with given prefix and suffix with maximum weight. If no word exists, return -1.

答案

class WordFilter {
    Map map = new HashMap<>();
    
    public WordFilter(String[] words) {
        for(int w = 0; w < words.length; w++) {
            for(int i = 0; i <= 10 && i <= words[w].length(); i++) {
                for(int j = 0; j <= 10 && j <= words[w].length(); j++) {
                    map.put(words[w].substring(0, i) + "/" + words[w].substring(words[w].length() - j), w);
                }
            }
        }
    }

    public int f(String prefix, String suffix) {
        String key = prefix + "/" + suffix;
        Integer lookup = map.get(key);
        if(lookup == null) return -1;
        return lookup;
    }
}

你可能感兴趣的:(Prefix and Suffix Search)