Leetcode - 139 Word Break (Medium)
题目描述:给定一个字符串 s 与字典 wordDict,判断 s 是否能拆分成 wordDict 中的子字符串。
Input: s = "leetcode", wordDict = ["leet", "code"]
Output: true
Explanation: Return true because "leetcode" can be segmented as "leet code".
解题思路:定义状态 dp[i] 为 [0, i) 是否能被拆分,双重循环遍历子串是否能够被拆分成 [0, j) 和 [j, i)。
public boolean wordBreak(String s, List<String> wordDict) {
boolean[] dp = new boolean[s.length() + 1];
dp[0] = true;
for(int i = 0; i <= s.length(); i++){
for(int j = 0; j < i; j++){
if(dp[j] && wordDict.contains(s.substring(j, i))){
dp[i] = true;
break;
}
}
}
return dp[s.length()];
}