1. 程式人生 > >hihoCoder 1014 Trie樹【python版】

hihoCoder 1014 Trie樹【python版】

python版的簡單字典樹:

n = int(raw_input())
lis = []
for i in range(n):
    str = raw_input()
    lis.append(str)
trie = {}
for i in range(n):
    p=trie
    for ch in lis[i]:
        if not p.has_key(ch):
            p[ch] = [{}, 0]
        p[ch][1] += 1
        p = p[ch][0]
m = int(raw_input())
for i in range(m):
    str = raw_input()
    p = trie
    ans = 0;
    cnt=0;
    for ch in str:
        if not p.has_key(ch):
            break
        else:
            cnt+=1
            if cnt == len(str):
                ans = p[ch][1]
            p = p[ch][0]
    print ans