地址:http://oj.leetcode.com/problems/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"
.
动态规划子状态:在长为s.length()的数组中的某个地址x上,当dp[x]为true时(意味着s的到x为止的长度都可以由给定字典拼成),可以有状态转移。
动态规划状态转移:dp[x]为true根据字典判断出x之后的为true的位置y,当s.substr(x, y-x)存在字典中时,有dp[y]为true。
参考代码 c++:
class Solution {
public:
bool wordBreak(string s, unordered_set<string> &dict) {
if(dict.empty() || s.empty())
return false;
vector<bool>dp(s.length()+1, false);
dp[0]=true;
for(int i = 0; i<s.length(); ++i)
{
for(int j = 1; i+j<=s.length(); ++j)
{
if(dp[i] && dict.find(s.substr(i, j)) != dict.end())
{
dp[i+j]=true;
if(dp[s.length()])
return true;
}
}
}
return false;
}
};
Second trial, in C++
//Second trial, almost the same
class Solution {
public:
bool wordBreak(string s, unordered_set<string> &dict) {
if(s.empty() || dict.empty())
return NULL;
vector<bool>dp(s.length()+1, false);
dp[0] = true;
int wlen;
for(int i = 0; i<s.length(); ++i) {
for(auto it = dict.begin(); it != dict.end(); ++it) {
wlen = (*it).length();
if(dp[i]) {
if(i + wlen <= s.length() && s.substr(i, wlen)==*it)
dp[i+wlen] = true;
}
}
if(dp[s.length()])
return true;
}
return false;
}
};
Python:
class Solution:
# @param s, a string
# @param dict, a set of string
# @return a boolean
def wordBreak(self, s, dict):
if not s or not len(dict):
return False
dp = [True] + [False] * len(s)
for i in range(len(dp)):
for word in dict:
if dp[i] and i+len(word) <= len(s) and s[i:i+len(word)]==word :
dp[i+len(word)] = True
if dp[len(s)]:
return True
return False