类别归档:LeetCode

LeetCode OJ is a platform for preparing technical coding interviews.

RSS feed of LeetCode

[LeetCode]Implement Trie (Prefix Tree)

题目描述:

Implement a trie with insert, search, and startsWith methods.

Note:
You may assume that all inputs are consist of lowercase letters a-z.

题目大意:

实现字典树,包含插入,查找和前缀查找方法。

注意:

你可以假设所有的输入只包含小写字母a-z

解题思路:

本题考查字典树数据结构的基础知识。

Trie使用孩子表示法存储,TrieNode为字典树的节点,包含属性childs和isWord。

其中childs为dict,存储当前节点的后代节点;isWord为布尔值,表示当前节点是否存储了一个单词。

Python代码:

class TrieNode:
    # Initialize your data structure ...

继续阅读

[LeetCode]Reverse Linked List

题目描述:

Reverse a singly linked list.

Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?

题目大意:

单链表逆置

提示:
用递归和迭代方式分别实现。

解题思路:

链表基本操作,递归方式参考:https://leetcode.com/discuss/34474/in-place-iterative-and-recursive-java-solution

Python代码:

迭代版本:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, ...

继续阅读

[LeetCode]Count Primes

题目描述:

Count the number of prime numbers less than a non-negative number, n

Hint: The number n could be in the order of 100,000 to 5,000,000.

References:

How Many Primes Are There? (https://primes.utm.edu/howmany.html)

Sieve of Eratosthenes (http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes)

题目大意:

统计小于非负整数n的素数的个数

提示:n的范围是100,000到5,000,000 ...

继续阅读