码迷,mamicode.com
首页 > 其他好文 > 详细

Word Break

时间:2014-08-18 18:40:22      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:算法   dp   

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




Word Break,布布扣,bubuko.com

Word Break

标签:算法   dp   

原文地址:http://blog.csdn.net/dutsoft/article/details/38662463

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!