[LeetCode] Prefix and Suffix Search (Java)
https://leetcode.com/problems/prefix-and-suffix-search/
입력 : 단어 배열 String[] words
출력 : 특정 접두사와 접미사를 가진 단어의 인덱스를 찾아 반환, 없으면 -1을 반환
O(n)
완전 탐색
구현
import java.util.*;
class WordFilter {
private Map<String, Integer> map;
public WordFilter(String[] words) {
map = new HashMap<>();
for (int index = 0; index < words.length; index++) {
String word = words[index];
int length = word.length();
for (int prefixLength = 0; prefixLength <= length; prefixLength++) {
String prefix = word.substring(0, prefixLength);
for (int suffixLength = 0; suffixLength <= length; suffixLength++) {
String suffix = word.substring(suffixLength);
map.put(prefix + "#" + suffix, index);
}
}
}
}
public int f(String prefix, String suffix) {
String key = prefix + "#" + suffix;
return map.getOrDefault(key, -1);
}
}
public class Main {
public static void main(String[] args) {
// Initialize the WordFilter with a list of words
String[] words = {"apple"};
WordFilter wf = new WordFilter(words);
// Call the f method and print the result
System.out.println(wf.f("a", "e")); // Expected output: 0
System.out.println(wf.f("b", "")); // Expected output: -1
}
}