题目:
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"
.
解题思路:
这是一道DP题,说实话,本人也是算法方面的菜鸟一枚,关于DP方面的题,还不太会解,没办法,只能多练习了。
这里采用DP中的自底向上实现,dp[i]表示前i个字符能否进行Wordbreak。当求解dp[i]时,可利用已经求解的dp[i-1],
dp[i-2]…dp[1],dp[0]进行求解。
对于dp[n]的求解,我们可以将n个字符进行切分求解,分为前i个字符和后n-i个字符,i可以为(0,1,2,3,4…n-1)
假设i为1时,可根据dp[i]和后面的n-1个字符组成的单词是否在dict中来判断dp[n],只要i(0,1,2,3,4…n-1)其中一种
情况为真,则dp[n]为true,表示可以进行workbreak。
实现代码:
#include <iostream> #include <string> #include <vector> #include <unordered_set> using namespace std; /* 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". */ class Solution { public: bool wordBreak(string s, unordered_set<string> &dict) { if(s.size() == 0 || dict.size() == 0) return false; int len = s.size(); vector<bool> dp(len+1, false);//保存状态,dp[i]表示前i个字符是否可以进行wordBread dp[0] = true; for(int i = 1; i <= len; i++) for(int j = 0; j < i; j++) { if(dp[j] && dict.count(s.substr(j, i-j)) == 1)//对前i个字符进行切分时,只要有一种情况为true,则dp[i]=true { dp[i] = true; break; } } return dp[len]; } bool wordBreak2(string s, unordered_set<string> &dict) { if(s.size() == 0 || dict.size() == 0) return false; int len = s.size(); vector<bool> dp(len+1, false);//保存状态,dp[i]表示前i个字符是否可以进行wordBread dp[0] = true; for(int i = 0; i < len; i++) if(dp[i]) { for(int j = 1; j <= len-i; j++) if(dict.count(s.substr(i, j)) == 1) dp[i+j] = true; } return dp[len]; } }; int main(void) { string s("leetcode"); unordered_set<string> dict; dict.insert("leet"); dict.insert("code"); Solution solution; bool ret = solution.wordBreak(s, dict); cout<<ret<<endl; return 0; }
LeetCode139:Word Break,布布扣,bubuko.com
原文:http://www.cnblogs.com/mickole/p/3672108.html