您的位置:首页 > 其它

leetcode--Word Break

2017-08-08 12:44 344 查看
Given a string s and a dictionary of words dict, determine ifs 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"
.

题意:给定一个字符串s,和字典,判断s能否由字典内的一个或者多个单词组合而成。

分类:动态规划

解法1:动态规划。使用flag[i]来表示从0到i构成的子串能否用字典来表示,那么我们要求的就是flag[s.length()]

对于flag[i],它由flag[j]和s.substring(j,i)这个子串决定,如果i之前存在一个j,使flag[j]为true,那么我们只要判断j到i这部分子串,是否在字典里面

如果在,那么显然flag[i]也为true

[java] view
plain copy

public class Solution {  

    public boolean wordBreak(String s, Set<String> wordDict) {  

        if(s.length()==0) return true;  

        if(wordDict.isEmpty()) return false;  

        boolean flag[] = new boolean[s.length()+1];  

        flag[0] = true;  

        for(int i=1;i<=s.length();i++){  

            for(int j=i-1;j>=0;j--){  

                if(flag[j]&&wordDict.contains(s.substring(j,i))){//判断子串  

                    flag[i] = true;  

                    break;  

                }  

            }  

        }  

        return flag[s.length()];  

    }  

}  

原文链接http://blog.csdn.net/crazy__chen/article/details/46563687
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: