Advertisement
imashutosh51

Word break

Oct 8th, 2022 (edited)
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.18 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.  
  14. unordered_map<string,int> mp;
  15. int fun(string s,int l,int dp[]){
  16.     if(l==s.size()) return 1;
  17.     if(dp[l]!=-1) return dp[l];
  18.     for(int i=l;i<s.size();i++){
  19.         if(mp[s.substr(l,i-l+1)] && fun(s,i+1,dp)==1){ dp[l]=1;return dp[l];}
  20.     }
  21.     dp[l]=false;
  22.     return dp[l];
  23. }
  24. class Solution {
  25. public:
  26.     bool wordBreak(string s, vector<string>& word){
  27.         mp.clear();
  28.         for(auto itr:word) mp[itr]++;
  29.         int dp[s.size()+1];
  30.         memset(dp,-1,sizeof(dp));
  31.         if(fun(s,0,dp)==1) return true;
  32.         else return false;
  33.     }
  34. };
  35.  
  36.    
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement