classSolution:defwordBreak(self,s:str,wordDict: List[str]) ->bool: wordDict =set(wordDict)@cachedefdp(pos):if pos ==len(s):returnTrue cur =''for nxt inrange(pos, len(s)): cur += s[nxt]if cur in wordDict anddp(nxt +1):returnTruereturnFalsereturndp(0)
JS Code:
/** * @param{string} s * @param{string[]} wordDict * @return{boolean} */varwordBreak=function (s, wordDict) {constdp=Array(s.length+1); dp[0] =true;for (let i =0; i <s.length+1; i++) {for (let word of wordDict) {if (word.length<= i && dp[i -word.length]) {if (s.substring(i -word.length, i) === word) { dp[i] =true; } } } }return dp[s.length] ||false;};
CPP Code:
classSolution {public:boolwordBreak(string s,vector<string>& dict) { unordered_set<string>st(begin(dict),end(dict));int N =s.size(); vector<bool>dp(N +1);dp[0] =true;for (int i =1; i <= N; ++i) {for (int j =0; j < i &&!dp[i]; ++j) {dp[i] =dp[j] &&st.count(s.substr(j, i - j)); } }returndp[N]; }};