From : https://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"
.
class Solution {
public:
bool wordBreak(string s, unordered_set<string> &dict) {
int n = s.size();
// dp[i]:i之前(不含i)已保证匹配成功
vector<bool> dp(n+1, false);
dp[0]=true;
for(int i=0;i<n;i++) {
// 查看0~i是否可以匹配
if(dp[i]) {
int idx=i;
for(int j=idx;j<n;j++) {
string cur=s.substr(idx,j-idx+1);
if(dict.find(cur) != dict.end())
dp[j+1]=true;
}
}
}
return dp[n];
}
};
public class Solution {
public boolean wordBreak(String s, Set<String> wordDict) {
if (s == null || wordDict == null) {
return false;
}
int n = s.length();
// dp[i]:i之前(不含i)已保证匹配成功
boolean[] containTo = new boolean[n + 1];
containTo[0] = true;
for (int i = 0; i < n; ++i) {
// 查看0~i是否可以匹配
if (containTo[i]) {
for (int j = i; j < n; j++) {
String cur = s.substring(i, j + 1);
if (wordDict.contains(cur)) {
containTo[j + 1] = true;
}
}
}
if (containTo[n] == true) {
return true;
}
}
return containTo[n];
}
}