Advertisement
smj007

Untitled

Feb 14th, 2024
913
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.01 KB | None | 0 0
  1. class Solution:
  2.     def wordBreak(self, s: str, wordDict: List[str]) -> bool:
  3.  
  4.         n = len(s)
  5.         dp = [False]*(len(s)+1)
  6.         dp[0] = True
  7.  
  8.         for i in range(1,n+1):
  9.             for word in wordDict:
  10.                 if i-len(word)>=0 and s[i-len(word):i] == word and dp[i-len(word)]:
  11.  
  12.                     # dp[i] - represents wordBreak ending here
  13.                     # notice dp variable running counter for n+1 variable
  14.                     # cause dp[i] - means word break possible for ith character in string
  15.                     # onlt if dp[i-len(word)] is True and i-len(word):i, notice it is enough
  16.                     # to use i-len(word):i instead of i+1 because then when we are accounting for
  17.                     # for ith iterm in dp variable we essemtially accountting for string ending at i-1
  18.                     # now to account for i-1th character we need to go back from i to i-len(word)
  19.  
  20.                     dp[i] = dp[i-len(word)]
  21.                     break
  22.  
  23.         return dp[-1]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement