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"
.
时间复杂度O(n^2),空间复杂度O(n)
public class Solution {
public boolean wordBreak(String s, Set<String> dict) {
boolean[] match = new boolean[s.length()];
for(int i=0; i<s.length(); i++){
if(dict.contains(s.substring(0, i+1))){
match[i] = true;
continue;
}
for(int j=0; j<i; j++){
if(match[j] && dict.contains(s.substring(j+1, i+1))){
match[i] = true;
break;
}
}
}
return match[s.length()-1];
}
}