题解 | #单词拆分(一)#
单词拆分(一)
https://www.nowcoder.com/practice/c0d32c1ce5744472a01b2351a2c2767f
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param s string字符串
* @param dic string字符串一维数组
* @return bool布尔型
*/
public boolean wordDiv (String s, String[] dic) {
// write code here
if (s == null || s.length() < 1 || dic == null) {
return false;
}
Set<String> set = new HashSet<>(Arrays.asList(dic));
int n = s.length();
boolean[] dp = new boolean[n + 1];
dp[0] = true;
for (int i = 1; i <= n; i++) {
for (int j = 0; j < i; j++) {
if (dp[j] && set.contains(s.substring(j, i))) {
dp[i] = true;
break;
}
}
}
return dp[n];
}
}
查看9道真题和解析