imashutosh51

Word break

Oct 8th, 2022 (edited)
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.33 KB | None | 0 0
  1. '''
  2. Logic:
  3. 1.We pushed all the words into the map so that we can search words in O(1) time.
  4. 2.We are iterating through the string from the begining and if we get that string present
  5.  in map,we pass the further string in same function.If we get output as 1 means that
  6.  current break is possible.so we make our dp for that index as 1.
  7. 3.Before iterating,if we already have 0 or 1 output,means we have already tried to break
  8.  from here.so return that output.
  9.  
  10. Basicaly,DP[i] represents that String can be broken from ith position or not,for that if
  11. string after that can be broken,only then it is possible.
  12. '''
  13. def fun(str,l,dict,dp):
  14.     if l==len(str): #l==len(str) only when all the previous chars are already in the word dictionary
  15.         return True
  16.     if dp[l] is not None:
  17.         return dp[l]
  18.     for i in range(l,len(str)):
  19.         if str[l:i+1] in dict and fun(str,i+1,dict,dp):
  20.             dp[l]=True
  21.             return dp[l]
  22.     dp[l]=False
  23.     return dp[l]
  24.    
  25.  
  26. class Solution:
  27.     def wordBreak(self, s: str, dict: List[str]) -> bool:
  28.         dp=[None]*len(s) #here None is mandatory so that we can know while returning dp[l] before for loop that has it been gone in recursion or not else if False we will keep,everytime we will return True even though some split is false
  29.         return fun(s,0,dict,dp)
  30.        
  31.    
Advertisement
Add Comment
Please, Sign In to add comment