视频讲解
代码
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
"""
Solution-0: BF Recursion
"""
# def helper(s, curr_idx) -> bool:
# if curr_idx == len(s) :
# return True
# N = len(s)
# for word in wordDict:
# if len(word) <= N - curr_idx and s[curr_idx:curr_idx+len(word)] in wordDict and helper(s,curr_idx+len(word)):
# return True
# return False
# return helper(s, 0)
"""
Solution-1: Recursion with memory
"""
# mem = {}
# def helper(s, curr_idx) -> bool:
# if curr_idx in mem:
# return mem[curr_idx]
# if curr_idx == len(s) :
# mem[curr_idx] = True
# return True
# N = len(s)
# for word in wordDict:
# if len(word) <= N - curr_idx and s[curr_idx:curr_idx+len(word)] in wordDict and helper(s,curr_idx+len(word)):
# mem[curr_idx] = True
# return True
# mem[curr_idx] = False
# return False
# return helper(s, 0)
"""
Solution-2: BFS( time out limit error)
"""
# queue = collections.deque([0])
# while queue:
# idx = queue.popleft()
# # print(idx)
# if idx == len(s):
# return True
# for end in range(idx, len(s) ):
# if s[idx:end+1] in wordDict:
# queue.append(end+1)
# return False
"""
Solution-3: Dynamic Programming
"""
dp = [False] * (len(s) + 1)
dp[0] = True
for i in range(len(s) + 1):
if dp[i]:
for word in wordDict:
if s[i:i+len(word)] == word:
dp[i+len(word)] = True
return dp[-1]
PPT讲解
本题涉及的知识点:
我的 Leetcode 讲解频道
代码链接
面试高频考点Youtube链接
- 数组(Array)
- 哈希表(Hash Table)
- 链表(Linked List)
- 数学(Math)
- 链表(Linked List)
- 双指针(Two Pointers)
- 字符串(String)
- 二分查找(Binary Search)
- 分治(Divide and Conquer)
- 动态规划(Dynamic Programming)
- 回溯(Backtracking)
- 栈(Stack)
- 堆(Heap)
- 贪心算法(Greedy)
- 排序(Sort)
- 树(Tree)
- 深度优先搜索(Depth-First Search)
- 广度优先搜索(Breadth-First Search)
- 二叉查找树(Binary Search Tree)
- 递归(Recursion)
- 队列(Queue)
- 移动窗口(Sliding Window)