Design a special dictionary that searches the words in it by a prefix and a suffix.
Implement the WordFilter class:
WordFilter(string[] words) Initializes the object with the words in the dictionary.
f(string pref, string suff) Returns the index of the word in the dictionary, which has the prefix pref and the suffix suff. If there is more than one valid index, return the largest of them. If there is no such word in the dictionary, return -1.
문자열 배열과 prefix 단어, suffix 단어가 입력으로 주어졌을때, 해당 prefix 와 suffix 를 동시에 가지고 있는 단어 인덱스를 반환해야한다. 만약 유효한 인덱스가 여러개 이면 최대값을 반환한다.
package leetcode;
import java.util.HashMap;
import java.util.Map;
public class Prefix_and_Suffix_Search {
private Map<String, Integer> map = new HashMap<>();
public Prefix_and_Suffix_Search (String[] words) {
for (int i = 0; i < words.length; i++) {
String word = words[i];
int length = word.length();
for (int j = 1; j <= length; j++) {
for (int k = 1; k <= length; k++) {
String key = word.substring(0, j) + "{" + word.substring(length - k);
map.put(key, i);
}
}
}
}
public int f(String pref, String suff) {
String s = pref + "{" + suff;
return map.getOrDefault(s, -1);
}
}