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"
.
class Solution {
public:
bool wordBreak(string s, unordered_set<string> &dict) {
bool* dp = new bool[s.size() + 1];//匹配子串的尾字符对应的下标的dp标记为true
memset(dp,false,s.size() + 1);
dp[0] = true;
for(int i = 1 ; i<s.size()+1 ; i++)
{
for(int j = 0; j < i; j++)
{
if(dp[j])
{
dp[i] = (dict.find(s.substr(j,i-j)) != dict.end())?true:false | dp[i];
if(dp[i])
continue;
}
}
}
return dp[s.size()];
}
};
用动态规划的思想,标记每个匹配的子串,如果字符串的最后一个字符对应的dp数组项为true,说明匹配成功。
例:
s = "leetcode"
,
dict = ["leet", "code"]
.
dp大小为s.size()+1 = 9
dp最终为{true,false,false,false,true,false,false,false,true}
dp[8] = true;
所以,匹配成功
已AC 48ms