LeetCode 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"
.
思路一,动态规划(DP):对于字符串s = "leetcode",对其进行划分的位置可以表示为:_l_e_e_t_c_o_d_e_,其中每个‘_’表示可以进行划分的位置。设定dp数组表示所有可能的划分位置,dp[i]表示由s[0]-s[i-1]组成的字串能否满足题意(这便是子问题),然后叠代此子结构,一直到dp[s.length()],便得到结果。
class Solution {
public:
bool wordBreak(string s, unordered_set<string>& wordDict) {
vector<bool> dp(s.length() + 1, false);
dp[0] = true;
for (int i = 1; i <= s.length(); i++)
{
for (int j = i-1; j >= 0; j--)
{
if (dp[j] == true)
{
string word = s.substr(j, i-j);
if (wordDict.find(word) != wordDict.end())
{
dp[i] = true;
break;
}
}
}
}
return dp[s.length()];
}
};
思路二,搜索
bool wordBreak(string s, unordered_set<string>& wordDict)
{
queue<int> q;//保存满足要求划分的下标
unordered_set<int> visited;
q.push(0);
while (q.size() > 0)
{
int start = q.front();
q.pop();
if (visited.find(start) == visited.end())
{
visited.insert(start);//标记已访问
for (int j = start; j<s.size(); j++)//搜索从start开始,所有可能的子串
{
string word(s, start, j - start + 1);//从start开始,判断后面的每个可能的子串
if (wordDict.find(word) != wordDict.end())//子串满足要求,则加入队列
{
q.push(j + 1);
if (j + 1 == s.size())
return true;
}
}
}
}
return false;
}