基础算法模板
tire树
#版本一:
class Tire:
def __init__(self):
self.tire = [0, {}]
def insert(self, word):
p = self.tire
for char in word:
if char not in p[1]:
p[1][char] = [0, {}]
p = p[1][char]
p[0] += 1
def query(self, word):
p = self.tire
for char in word:
if char not in p[1]:
return 0
else:
p = p[1][char]
return p[0]
if __name__ == "__main__":
n = int(input())
T = Tire()
for _ in range(n):
op, word = input().split()
if op == "I":
T.insert(word)
else:
print(T.query(word))
#版本二
N = 10 ** 5 + 10
n = int(input())
tire = [[0 for _ in range(27)] for _ in range(N)]
cnt = [0] * N
idx = 0
def insert(word):
global idx
p = 0
for char in word:
u = ord(char) - ord('a')
if tire[p][u] == 0:
idx += 1
tire[p][u] = idx
p = tire[p][u]
cnt[p] += 1
def query(word):
p = 0
for char in word:
u = ord(char) - ord('a')
if tire[p][u] == 0:
return 0
else:
p = tire[p][u]
return cnt[p]
for _ in range(n):
op, word = input().split()
if op == "I":
insert(word)
else:
print(query(word))
KMP
n = int(input())
s = " " + input()
m = int(input())
t = " " + input()
ne = [0] * 100010
j = 0
for i in range(2, n + 1):
while j and s[i] != s[j + 1]:
j = ne[j]
if s[i] == s[j + 1]:
j += 1
ne[i] = j
j = 0
for i in range(1, m + 1):
while j and t[i] != s[j + 1]:
j = ne[j]
if t[i] == s[j + 1]:
j += 1
if j == n:
print(i - j, end =' ')
j = ne[j]
单调栈
n = input()
nums = list(map(int, input().split()))
deq = []
for i in range(len(nums)):
while deq and deq[-1] >= nums[i]:
deq.pop()
if len(deq) != 0:
print(deq[-1], end = " ")
else:
print(-1, end = " ")
deq.append(nums[i])