更新 0139.单词拆分.md Java代码

使用Set容器加速两层for循环中的查询函数,原代码在List列表中查询,本质上为三层循环,使用Set容器后为两层循环
This commit is contained in:
zhicheng lee
2022-09-13 22:21:15 +08:00
committed by GitHub
parent 90411f13f1
commit 0dad9a5f7c

View File

@ -234,11 +234,13 @@ Java
```java
class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
HashSet<String> set = new HashSet<>(wordDict);
boolean[] valid = new boolean[s.length() + 1];
valid[0] = true;
for (int i = 1; i <= s.length(); i++) {
for (int j = 0; j < i; j++) {
if (wordDict.contains(s.substring(j,i)) && valid[j]) {
for (int j = 0; j < i && !valid[i]; j++) {
if (set.contains(s.substring(j, i)) && valid[j]) {
valid[i] = true;
}
}