classSolution{publicbooleanwordBreak(String s,List<String> wordDict){HashSet<String> set =newHashSet<String>(wordDict);boolean dp[]=newboolean[s.length()+1];
dp[0]=true;for(int j =1; j <= s.length(); j++){for(int i =0; i < j &&!dp[j]; i++){if(set.contains(s.substring(i,j))&& dp[i]) dp[j]=true;}}return dp[s.length()];}}
回溯
classSolution{privateint memo[];privateHashSet<String> set;publicbooleanwordBreak(String s,List<String> wordDict){
memo =newint[s.length()];
set =newHashSet<>(wordDict);returndfs(s,0);}publicbooleandfs(String s,int startIndex){if(startIndex == s.length()){returntrue;}if(memo[startIndex]==-1){returnfalse;}for(int i = startIndex; i < s.length(); i++){String sub = s.substring(startIndex, i +1);if(!set.contains(sub))continue;boolean res =dfs(s, i +1);if(res)returntrue;}
memo[startIndex]=-1;returnfalse;}}