首页 > 代码库 > Word Break
Word Break
Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
For example, given
s = "leetcode"
,
dict = ["leet", "code"]
.
Return true because "leetcode"
can be segmented as "leet code"
.
dfs,时间复杂度O(2^n),超时。
public class Solution { public boolean wordBreak(String s, Set<String> dict) { return dfs(0,s,dict); } public boolean dfs(int start,String s, Set<String> dict){ if(start==s.length()){ return true; } boolean res=false; for(int i=start;i<s.length();i++){ if(dict.contains( s.substring(start,i+1) )){ res|=dfs(i+1,s,dict); if(res) break; } } return res; } }dp
public class Solution { public boolean wordBreak(String s, Set<String> dict) { return dp(s,dict); } public boolean dp(String s, Set<String> dict){ if(s==null || s.length()==0) return true; int n=s.length(); boolean []f=new boolean[n+1]; f[0]=true; for(int i=1;i<=n;i++){ for(int j=i-1;j>=0;j--){ if( f[j] && dict.contains( s.substring(j,i) )){ f[i]=true; break; } } } return f[n]; } }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。