AcWing 142. 【Java】前缀统计
原题链接
简单
作者:
tt2767
,
2019-12-18 23:07:17
,
所有人可见
,
阅读 637
// 最后一个样例T了,本机跑374ms
// 周末试下上个题解讨论区同学的优化方法
import java.util.*;
public class Main{
class Tire{
int[][] str;
int[] end;
int idx;
public Tire(int n){
str = new int[n][26];
end = new int[n];
idx = 0;
}
public void set(String s){
int p = 0;
for (int i = 0 ; i < s.length(); i++){
int ch = s.charAt(i) - 'a';
if (str[p][ch] == 0) str[p][ch] = ++idx;
p = str[p][ch];
}
end[p] ++;
}
public int count(String s){
int p = 0;
int result = 0;
for (int i = 0 ; i < s.length() ; i++){
int ch = s.charAt(i) - 'a';
if (str[p][ch] == 0) break;
p = str[p][ch]; // 因为存的时候是end[p] 是按p的下一位存的,所以这里要放在统计前面
result += end[p];
}
return result;
}
}
void run(){
int n = jin.nextInt();
int m = jin.nextInt();
List<String> patterns = new ArrayList<>();
List<String> querys = new ArrayList<>();
for (int i = 0; i < n ; i++) patterns.add(jin.next());
for (int i = 0 ;i < m ; i++) querys.add(jin.next());
solve(patterns, querys);
}
void solve(List<String> patterns, List<String> querys){
Tire tire = new Tire(500000);
for (int i = 0 ; i < patterns.size(); i++){
tire.set(patterns.get(i));
}
for (int i = 0 ;i < querys.size() ; i++){
System.out.println(tire.count(querys.get(i)));
}
}
private Scanner jin = new Scanner(System.in);
public static void main(String[] args) throws Exception {new Main().run();}
}