1. 程式人生 > 實用技巧 >835.Trie字串統計

835.Trie字串統計

維護一個字串集合,支援兩種操作:
“I x”向集合中插入一個字串x;
“Q x”詢問一個字串在集合中出現了多少次。
共有N個操作,輸入的字串總長度不超過 105,字串僅包含小寫英文字母。

輸入格式

第一行包含整數N,表示運算元。
接下來N行,每行包含一個操作指令,指令為”I x”或”Q x”中的一種。

輸出格式

對於每個詢問指令”Q x”,都要輸出一個整數作為結果,表示x在集合中出現的次數。
每個結果佔一行。

資料範圍

1≤N≤2∗104

輸入樣例:

5
I abc
Q abc
Q ab
I ab
Q ab

輸出樣例:

1
0
1

參考程式碼

import java.util.Scanner;

public class Main {

	static int[][] son = new int[100010][26];
	static int[] cnt = new int[100010];
	static int idx = 0;

	public static void insert(char[] str) {
		int p = 0;
		for (int i = 0; i < str.length; i++) {
			int u = str[i] - 'a';
			if (son[p][u] == 0) {
				son[p][u] = ++idx;
			}
			p = son[p][u];
		}
		cnt[p]++;
	}

	public static int query(char[] str) {
		int p = 0;
		for (int i = 0; i < str.length; i++) {
			int u = str[i] - 'a';
			if (son[p][u] == 0) {
				return 0;
			}
			p = son[p][u];
		}
		return cnt[p];
	}

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);

		int n = Integer.parseInt(sc.nextLine());
		while ((n--) != 0) {
			String str = sc.nextLine();
			String[] t = str.split(" ");
			if (t[0].equals("I")) {
				insert(t[1].toCharArray());
			} else {
				System.out.println(query(t[1].toCharArray()));
			}
		}

		sc.close();
	}
}