Word Break

来源:互联网 发布:envi处理landsat8数据 编辑:程序博客网 时间:2024/05/29 01:52

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];    }}




0 0
原创粉丝点击