def wordBreak(self, s: str, wordDict: List[str]) -> bool:
class solutionFound(Exception):
pass
def dfs(s):
if len(s) == 0:
raise solutionFound
for i in range(len(wordDict)):
if s.startswith(wordDict[i]):
dfs(s[len(wordDict[i]):])
try:
dfs(s)
return False
except solutionFound:
return True
In the code above, I’m making a lot of recursive calls inside the function and I just want to return immediately when a solution is found. One way to go about it is to use exception, I was just wondering if there is another way to achieve this with minimal code.
>Solution :
Your code should return True as soon as the base case is reached or False whenever the recursion finishes without any successful result. By doing this, the recursion will stop when the first result is found.
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
def dfs(s):
if len(s) == 0:
return True
for i in range(len(wordDict)):
if s.startswith(wordDict[i]):
if dfs(s[len(wordDict[i]):]):
return True
return False
return dfs(s)