class StreamChecker:
def __init__(self, words: 'List[str]'):
self.maxLen = 0
self.List = set(words)
for w in self.List:
self.maxLen = max(self.maxLen,len(w))
self.STR = '' def query(self, letter: str) -> bool: if letter in self.List:
return True
else:
self.STR += letter clen = len(self.STR)
if clen > self.maxLen:
self.STR = self.STR[1:] for w in self.List:
lw = len(w)
ls = len(self.STR)
if ls >= lw and w == self.STR[ls-lw:]:
return True
return False

此解决方案超时:

在上面的代码基础上,增加Trie数据结构,解决方案如下:

 class Node:
def __init__(self):
self.isWord = False
self.next = [0]*26 class StreamChecker:
def __init__(self, words: 'List[str]'):
self.maxLen = 0
self.Trie = Node()
dwords = set(words)
for w in dwords:
cur = self.Trie
for i in range(len(w)-1,-1,-1):
c = w[i]
index = ord(c) - ord('a')
if not cur.next[index]:
cur.next[index] = Node()
cur = cur.next[index]
if i == 0:
cur.isWord = True
self.maxLen = max(self.maxLen,len(w))
self.STR = '' def query(self, letter: str) -> bool:
self.STR += letter
clen = len(self.STR)
if clen > self.maxLen:
self.STR = self.STR[1:] cur = self.Trie
for i in range(len(self.STR)-1,-1,-1):
c = self.STR[i]
index = ord(c) - ord('a')
if not cur.next[index]:
return False
else:
cur = cur.next[index]
if cur.isWord:
return True
return False

leetcode1032的更多相关文章

  1. [Swift]LeetCode1032. 字符流 | Stream of Characters

    Implement the StreamChecker class as follows: StreamChecker(words): Constructor, init the data struc ...

随机推荐

  1. ionic1 添加百度地图插件 cordova-plugin-baidumaplocation

    cordova-plugin-baidumaplocation 这个插件返回的数据是 json 格式的  可以直接获取  android 和 ios 都可用 1.先去百度地图平台去创建应用  获取访问 ...

  2. wc语法

    统计当前目录下的所有文件行数: wc -l * 当前目录以及子目录的所有文件行数: find  . * | xargs wc -l 可以把*改成所要匹配的文件,例如Java文件,*.java这样就只统 ...

  3. 自由线程FreeThreadDOMDocument

    Posted on 2006年09月4日by 不及格的程序员-八神 星期二 天气:晴   昨天燕子 自己去五爱了 给我买了一堆袜子 给妈买了一双鞋 给自己买了一件 红色的内衣服 挺好看的 在市场买了一 ...

  4. gpu/mxGPUArray.h” Not Found

    https://cn.mathworks.com/matlabcentral/answers/294938-cannot-find-lmwgpu More specifically change th ...

  5. 【Java】字节数组转换工具类

    import org.apache.commons.lang.ArrayUtils; import java.nio.charset.Charset; /** * 字节数组转换工具类 */ publi ...

  6. 通过位运算求两个数的和(求解leetcode:371. Sum of Two Integers)

    昨天在leetcode做题的时候做到了371,原题是这样的: 371. Sum of Two Integers Calculate the sum of two integers a and b, b ...

  7. OpenCV中图像的格式Mat 图像深度

    opencv中图像的格式Mat 有图像的定义,图像深度.类型格式等,其中Mat的参数depth为深度,深度反应出图像颜色像素值: 关于数据的储存:(转) Mat_<uchar>对应的是CV ...

  8. Gym - 101617F :Move Away (圆的交点)

    pro:给定N个圆,求离原点最远的点,满足它在N个圆里.输出这个距离.N<50; sol:关键点一定是圆与圆的交点. 圆与 圆心到原点的直线 的交点. 然后去验证这些关键点是否在N个圆内. 实际 ...

  9. Codeforces1062A. A Prank(暴力)

    题目链接:传送门 题目: A. A Prank time limit per test second memory limit per test megabytes input standard in ...

  10. Java基于opencv实现图像数字识别(一)

    Java基于opencv实现图像数字识别(一) 最近分到了一个任务,要做数字识别,我分配到的任务是把数字一个个的分开:当时一脸懵逼,直接百度java如何分割图片中的数字,然后就百度到了用Buffere ...