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.