LeetCode-139.Word Break

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

动态规划问题:

关键是得到递推式

res[i]是表示到字符串s的第i个元素为止能不能用字典中的词来表示,我们需要一个长度为n的布尔数组来存储信息。然后假设我们现在拥有res[0,...,i-1]的结果,我们来获得res[i]的表达式。思路是对于每个以i为结尾的子串,看看他是不是在字典里面以及他之前的元素对应的res[j]是不是true,如果都成立,那么res[i]为true

 public bool WordBreak(string s, ISet<string> wordDict)
    {
        if (s == null || s.Length == 0)
                return true;
            bool[] res = new bool[s.Length + 1];
            res[0] = true;
            for (int i = 0; i < s.Length; i++)
            {
                StringBuilder str = new StringBuilder(s.Substring(0, i + 1));
                for (int j = 0; j <= i; j++)
                {
                    if (res[j] && wordDict.Contains(str.ToString()))
                    {
                        res[i + 1] = true;
                        break;
                    }
                    str.Remove(0,1);
                }
            }
            return res[s.Length];
    }

参考: http://blog.csdn.net/linhuanmars/article/details/22358863

你可能感兴趣的:(LeetCode,动态规划)