- 描述
Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. You may assume the dictionary does not contain duplicate words.
For example, given
s = “leetcode”,
dict = [“leet”, “code”].
Return true because “leetcode” can be segmented as “leet code”.
UPDATE (2017/1/4):
The wordDict parameter had been changed to a list of strings (instead of a set of strings). Please reload the code definition to get the latest changes.
- 思路
这道算法题参照了其他博主的思路:
https://www.cnblogs.com/reboot329/p/6168346.html
http://blog.csdn.net/feliciafay/article/details/18999903
这里主要是使用动态规划的思想去求解。首先求解出第i(i为0、1、2…..s.Length)个字符串是否符合题目要求,而第i个字符串符合要求有这样几种可能,第j(j为0、1、2…i-1)个字符串符合要求并且集合中包含s.Substring(j, i - j)字符串。下面给出代码 - 代码(c#)
public bool WordBreak(string s, IList<string> wordDict)
{
bool[] dp = new bool[s.Length + 1];//用于保存第i个字符串是否符合题目要求
dp[0] = true;
for (int i = 0; i <= s.Length ; i++)
{
for (int j = 0; j < i; j++)
{
if (dp[j] && wordDict.Contains(s.Substring(j, i - j)))//尝试寻找符合题意的组合
{
dp[i] = true;
break;
}
}
}
return dp[s.Length];
}