AcWing 835. 简洁java - HashMap模板 - Trie字符串统计
原题链接
简单
作者:
acw_weian
,
2020-04-20 21:23:58
,
所有人可见
,
阅读 931
HashMap模板
import java.io.*;
import java.util.*;
class Main{
static class Node{
char val;
int count;
Map<Character, Node> children;
Node(){}
Node(char val){
this.val = val;
}
}
static Node root;
public static void insert(String s){
Node node = root;
for(int i = 0; i < s.length(); i++){
char c = s.charAt(i);
if(node.children == null) node.children = new HashMap();
if(!node.children.containsKey(c)) node.children.put(c, new Node(c));
node = node.children.get(c);
}
node.count++;
}
public static int search(String s){
Node node = root;
for(int i = 0; i < s.length(); i++){
char c = s.charAt(i);
if(node.children == null || !node.children.containsKey(c)) return 0;
node = node.children.get(c);
}
return node.count;
}
static BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
static BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out));
public static void main(String[] args) throws Exception{
int n = Integer.valueOf(read.readLine());
String[] s;
root = new Node();
for(int i = 0; i < n; i++){
s = read.readLine().split(" ");
if("I".equals(s[0])){
insert(s[1]);
}else{
log.write(search(s[1]) + "\n");
}
}
log.flush();
}
}
y总模板
import java.io.*;
class Main{
static BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
static BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out));
static int N = 100010, idx = 0;
static int[][] trie = new int[N][26];
static int[] cnt = new int[N];
public static void insert(char[] cs){
int p = 0;
for(int i = 0; i < cs.length; i++){
int t = cs[i] - 'a';
if(trie[p][t] == 0) trie[p][t] = ++idx;
p = trie[p][t];
}
cnt[p]++;
}
public static int query(char[] cs){
int p = 0;
for(int i = 0; i < cs.length; i++){
int t = cs[i] - 'a';
if(trie[p][t] == 0) return 0;
p = trie[p][t];
}
return cnt[p];
}
public static void main(String[] args) throws Exception{
int t = Integer.valueOf(read.readLine());
while(t-- > 0){
String[] s = read.readLine().split(" ");
switch(s[0]){
case "I":
insert(s[1].toCharArray());
break;
case "Q":
log.write(query(s[1].toCharArray()) + "\n");
break;
}
}
log.flush();
}
}
不方便观赏
map能存上百万的数据吗?
当然 O(1e6)范围都可以
为什么switch改成if就全是0啊
java 不能直接==判断,需要用equals判断