题目描述
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中任意子串是否包含dict中的单词
- DFS从后往前匹配
import java.util.*;
public class Solution {
int[][] dp;
public boolean wordBreak(String s, Set<String> dict) {
int len = s.length();
dp = new int[len][len];
for (int i = 0; i < len; i++) {
for (int j = i; j < len; j++) {
String temp = s.substring(i, j + 1);
if (dict.contains(temp)) {
dp[i][j] = 1;
}
}
}
return dfs(len - 1);
}
public boolean dfs(int length) {
if (length == -1) {
return true;
}
boolean flag = false;
for (int i = 0; i <= length; i++) {
if (dp[i][length] == 1) {
flag |= dfs(i - 1);
}
}
return flag;
}
}