트라이
트라이는 문자열 검색을 빠르게 실행할 수 있도록 설계한 트리 형태의 자료구조이다.
문자열 찾기
Question - 14425
Code
import java.util.Scanner;
public class N69_P14425_문자열_찾기 {
// 문자열
// 검색 문자열
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int word = sc.nextInt();
int search = sc.nextInt();
wNode root = new wNode();
while (word > 0) {
String text = sc.next();
wNode now = root;
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (now.next[c - 'a'] == null) {
now.next[c - 'a'] = new wNode();
}
now = now.next[c - 'a'];
// 마지막 chart이면
if (i == text.length() - 1)
now.isEnd = true;
}
word--;
}
int count = 0;
while (search > 0) {
String text = sc.next();
wNode now = root;
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (now.next[c - 'a'] == null)
break;
now = now.next[c - 'a'];
if (i == text.length() - 1 && now.isEnd)
count++;
}
search--;
}
System.out.println(count);
}
}
class wNode {
wNode[] next = new wNode[26];
boolean isEnd;
}
Insight
중간부터 시작하는 단어 검색하는 경우는 ?
Idea
reference
Last updated