1. 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".
博文Word Break -- LeetCode提及了动态规划的思想:
首先我们要决定要存储什么历史信息以及用什么数据结构来存储信息。然后是最重要的递推式,就是如从存储的历史信息中得到当前步的结果。最后我们需要考虑的就是起始条件的值。
下边是该博文对该题目的分析:
首先我们要存储的历史信息res[i]是表示到字符串s的第i个元素为止能不能用字典中的词来表示,我们需要一个长度为n的布尔数组来存储信息。然后假设我们现在拥有res[0,...,i-1]的结果,我们来获得res[i]的表达式。思路是对于每个以i为结尾的子串,看看他是不是在字典里面以及他之前的元素对应的res[j]是不是true,如果都成立,那么res[i]为true,写成式子是
具体程序如下:
1 class Solution { 2 public: 3 bool wordBreak(string s, unordered_set<string>& wordDict) { 4 int szS = s.size(); 5 if(szS == 0) 6 return false; 7 8 vector<bool> dp(szS + 1, false); 9 dp[0] = true; 10 for(int i = 1; i < szS + 1; i++) 11 { 12 for(int j = i - 1; j > -1; j--) 13 { 14 if(dp[j] && wordDict.find(s.substr(j, i - j)) != wordDict.end()) 15 { 16 dp[i] = true; 17 break; 18 } 19 } 20 } 21 22 return dp[szS]; 23 } 24 };