Optimized one: mainly index using

    1. class Solution:
    2. def wordBreak(self, s: str, wordDict: List[str]) -> bool:
    3. if not s:
    4. return False
    5. n = len(s)
    6. dp = [False] * (n + 1)
    7. dp[0] = True
    8. for j in range(1, n+1):
    9. for h in range(j):
    10. if dp[h] and s[h:j] in wordDict:
    11. dp[j] = True
    12. break
    13. print(dp)
    14. return dp[-1]

    My first solution

    1. class Solution:
    2. def wordBreak(self, s: str, wordDict: List[str]) -> bool:
    3. if not s:
    4. return False
    5. n = len(s)
    6. dp = [False] * n
    7. for j in range(n):
    8. if s[0:j+1] in wordDict:
    9. dp[j] = True
    10. continue
    11. for h in range(j):
    12. if dp[h] and s[h+1:j+1] in wordDict:
    13. dp[j] = True
    14. #print(dp)
    15. return dp[n-1]