LeetCode -- Word Break

Question:

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".

 

Analysis:

给出一个字符串s和一个词典dict,判断s是否是由词典中词组成的一个字符串序列。

思路:

我们想知道整个句子是否是有词典中的词构成的,则很容易想到希望知道去掉最后一个字符构成的字符串是否满足条件,依次往前类推。这样很容易想到使用动态规划。

如果某个位置i处是由词典中的词语构成的,并且从i处到j处又刚刚好构成一个词,这个词也在词典中出现,则j之前的所有字符串一定是满足条件的,

因此状态转移方程为:

dp[j] = dp[i] && dict.contains(s.subString(i, j));

这样从开始处遍历整个字符串,得到整个dp数组。

 

代码为:

import java.util.Set;
public class Solution {
    public boolean wordBreak(String s, Set<String> wordDict) {
        if(s == null || s.length() == 0) return false;
        int len = s.length();
        boolean[] dp = new boolean[len+1];
        dp[0] = true;
        for(int i=1; i<=len; i++) {
            for(int j=0; j<i; j++) {
                if(dp[j] && wordDict.contains(s.substring(j, i))) {
                    dp[i] = true;
                    break;
                }
            }
        }
        return dp[len];
    }
}

 

posted @ 2016-04-14 16:06  江湖小妞  阅读(316)  评论(0编辑  收藏  举报