原题

以下是我的代码,就是简单的字符串操作,可以ac但背离了题意,我之前没接触过Trie

 1 class Trie:
2
3 def __init__(self):
4 """
5 Initialize your data structure here.
6 """
7 self.trie = set()
8
9 def insert(self, word: str) -> None:
10 """
11 Inserts a word into the trie.
12 """
13 self.trie.add(word)
14
15 def search(self, word: str) -> bool:
16 """
17 Returns if the word is in the trie.
18 """
19 return word in self.trie
20
21 def startsWith(self, prefix: str) -> bool:
22 """
23 Returns if there is any word in the trie that starts with the given prefix.
24 """
25 lens = len(prefix)
26 for s in self.trie:
27 if s[:lens] == prefix:
28 return True
29 return False
30
31
32 # Your Trie object will be instantiated and called as such:
33 # obj = Trie()
34 # obj.insert(word)
35 # param_2 = obj.search(word)
36 # param_3 = obj.startsWith(prefix)

以下是大佬写的,答案链接

 1 class Trie {
2 private:
3 bool isEnd;
4 Trie* next[26];
5 public:
6 Trie() {
7 isEnd = false;
8 memset(next, 0, sizeof(next));
9 }
10
11 void insert(string word) {
12 Trie* node = this;
13 for (char c : word) {
14 if (node->next[c-'a'] == NULL) {
15 node->next[c-'a'] = new Trie();
16 }
17 node = node->next[c-'a'];
18 }
19 node->isEnd = true;
20 }
21
22 bool search(string word) {
23 Trie* node = this;
24 for (char c : word) {
25 node = node->next[c - 'a'];
26 if (node == NULL) {
27 return false;
28 }
29 }
30 return node->isEnd;
31 }
32
33 bool startsWith(string prefix) {
34 Trie* node = this;
35 for (char c : prefix) {
36 node = node->next[c-'a'];
37 if (node == NULL) {
38 return false;
39 }
40 }
41 return true;
42 }
43 };

最新文章

  1. android 设置布局横屏竖屏
  2. 檢查RAC狀態
  3. C#记录对象的变化
  4. 【Android测试】【第九节】MonkeyRunner—— 初识
  5. ThreadLocal深入理解二
  6. 001 The Hello World In Csharp
  7. 求解:C#.Net 远程方法调用失败 (Exception from HRESULT: 0x800706BE)
  8. ShareSDK的简化压缩和使用样例
  9. 《Google软件测试之道》【PDF】下载
  10. [DevExpress使用随笔]之NavBarControl控件(一)【转】
  11. HTML---仿网易新闻登录页
  12. VitualBox安装linux记录
  13. python发送requests请求时,使用登录的token值,作为下一个接口的请求头信息
  14. oracle数据表中的中文变问号
  15. 7-性能测试i报告
  16. C语言从零开始(十四)-字符串处理
  17. IO流(10)复制多级文件夹
  18. Python 开发中高级技巧
  19. Consul 简介、安装、常用命令的使用
  20. Vuejs - 强大的指令系统

热门文章

  1. 【C#】对两张图片进行矩阵运算会怎么样?
  2. AYIT-2020 609暑假集训第一周周赛题 A - A计划
  3. Codeforces Round #652 (Div. 2) B. AccurateLee(字符串)
  4. 组合数取模及Lucas定理
  5. HDU - 2825 Wireless Password (AC自动机+状压DP)
  6. codeforces 580D. Kefa and Dishes
  7. Happy 2006 POJ - 2773 容斥原理+二分
  8. Codeforces Round #669 (Div. 2) B. Big Vova (枚举)
  9. Educational Codeforces Round 56 (Rated for Div. 2) D. Beautiful Graph (二分图染色)
  10. vue slot nested bug