139. Word Break
Problem description:
Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. You may assume the dictionary does not contain duplicate words.
For example, given
s = “leetcode”,
dict = [“leet”, “code”].
Return true because “leetcode” can be segmented as “leet code”.
UPDATE (2017/1/4):
The wordDict parameter had been changed to a list of strings (instead of a set of strings). Please reload the code definition to get the latest changes.
Solution:
The idea for the solution is that a given string s
can be divided into two substring s1
and s2
. If s1
and s2
both fulfill the requirement, then complete the problem. Let’s create a dp array, which dp[i]= 1
means we are able to find match in dictionary.
As we just said, the original string can treat as substrings. Therefore, we can use a two pointer to check whether if there’s matches in a string.
1 | class Solution: |
1 | class Solution { |
Second time:
similar idea from previous one.
1 | class Solution { |
Solution BFS
Modeled as a graph problem - every index is a vertex and every edge is a completed word
For example, the input string is “nightmare”, there are two ways to break it, “night mare” and “nightmare”. The graph would be1
2
30-->5-->9
|__ __ _^
The question is simply to check if there is a path from 0 to 9. The most efficient way is traversing the graph using BFS with the help of a queue and a hash set. The hash set is used to keep track of the visited nodes to avoid repeating the same work.
1 | class Solution: |