Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
For example, given
s = "leetcode"
,
dict = ["leet", "code"]
.
Return true because "leetcode"
can be segmented as "leet code"
.
Here is a simple example to under stand the code in detail.
http://www.codeskulptor.org/#user37_7mt6s7ux3U784tc.py
Again, I would definitely finish this code in a nasty way and waste a lot of precious time in my 'stupd' coding, which is not I want to do since I realize my fault a couple of days ago. Time to learn from the elite than work clumsily myself!
The idea is to use dynamic programming:
dynamic programming is a method for solving complex problems by breaking them down into simpler subproblems. It is applicable to problems exhibiting the properties of overlapping subproblems[1] and optimal substructure.
In general, to solve a given problem, we need to solve different parts of the problem (subproblems), then combine the solutions of the subproblems to reach an overall solution. Often when using a more naive method, many of the subproblems are generated and solved many times. The dynamic programming approach seeks to solve each subproblem only once, thus reducing the number of computations: once the solution to a given subproblem has been computed, it is stored or "memo-ized": the next time the same solution is needed, it is simply looked up.
class Solution:
# @param s, a string
# @param dict, a set of string
# @return a boolean
def wordBreak(self, s, dict):
break_rcrd = [False for dummy_index in range(len(s) + 1)]
break_rcrd[0] = [True]
for break_index in range(1, len(s)+1):
# chcek if s[0:break_index] in the dict
if s[0: break_index] in dict:
break_rcrd[break_index] = True
continue
# chck if the break parts of s[0:break_index] in the dict
for tmp_break_index in range(1, break_index):
if break_rcrd[tmp_break_index] == False:
# head is not breakable
# no need to check the rest
continue
if s[tmp_break_index:break_index] not in dict:
# the head is breakable
# but the rest part is not
# continue the next interation in for
continue
# head is breakable and rest parts in dict
# the words before/include break_index is breakable
break_rcrd[break_index] = True
break
return break_rcrd[-1]