您的位置:首页 > 编程语言 > Go语言

Word Break

2014-01-27 10:57 507 查看
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"
.

构造一个boolean数组来储存能够在字典中查到的字符串。

boolean数组的第一个index为额外起始点。

例如 "leetcode"

table = {false, false, false,false, true,false,false,false,true}

    public static boolean wordBreak(String s, Set<String> dict){
        boolean[] dp = new boolean[s.length()+1];
        for(int i = 0; i < s.length()+1; i++){
            for(int j = 0; j < i; j++){
                if(dict.contains(s.substring(j, i))){
                    if(j==0) dp[i] = true;
                    else if(dp[j]) dp[i] = true;
                }
            }
        }
        return dp[s.length()];
    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode algorithm