Link:
https://leetcode.com/problems/word-break/
My code:
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
if len(s) ==0:
return False
elif len(s) ==1:
if s[0] in wordDict:
return True
else:
return False
else:
TFList = [True]
InitialString = s[0]
if InitialString in wordDict:
TFList.append(True)
else:
TFList.append(False)
for i in range(1,len(s)):
ExitFlag = False
TFValue = TFList[i]
if TFValue == True:
String1 = s[i]
if String1 in wordDict:
TFList.append(True)
continue
else:
for j in range(1,(1+i)):
string2 = s[(i-j):i+1]
if TFList[i-j] ==True and string2 in wordDict:
ExitFlag = True
TFList.append(True)
break
if ExitFlag == True:
continue
else:
TFList.append(False)
else:
for j in range(1,(i+1)):
string2 = s[(i-j):(i+1)]
if TFList[i-j] ==True and string2 in wordDict:
ExitFlag = True
TFList.append(True)
break
if ExitFlag == True:
continue
else:
TFList.append(False)
return TFList[len(s)]
Explanation: The idea of my code is to recurse from the start of the string. For each extra string we attach to original string, there are two situations: 1. Old string can be broken by the given dictionary. In this case, we first test if the extra one string is in the dictionary. If true, then we return True for this substring. If not, we need to go back to test every case with strings divided by i-j the element. If one of them gives true, then we may return true, otherwise give false for that case.