mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 11:34:46 +08:00
更新 0139.单词拆分.md Java代码
使用Set容器加速两层for循环中的查询函数,原代码在List列表中查询,本质上为三层循环,使用Set容器后为两层循环
This commit is contained in:
@ -234,11 +234,13 @@ Java:
|
|||||||
```java
|
```java
|
||||||
class Solution {
|
class Solution {
|
||||||
public boolean wordBreak(String s, List<String> wordDict) {
|
public boolean wordBreak(String s, List<String> wordDict) {
|
||||||
|
HashSet<String> set = new HashSet<>(wordDict);
|
||||||
boolean[] valid = new boolean[s.length() + 1];
|
boolean[] valid = new boolean[s.length() + 1];
|
||||||
valid[0] = true;
|
valid[0] = true;
|
||||||
|
|
||||||
for (int i = 1; i <= s.length(); i++) {
|
for (int i = 1; i <= s.length(); i++) {
|
||||||
for (int j = 0; j < i; j++) {
|
for (int j = 0; j < i && !valid[i]; j++) {
|
||||||
if (wordDict.contains(s.substring(j,i)) && valid[j]) {
|
if (set.contains(s.substring(j, i)) && valid[j]) {
|
||||||
valid[i] = true;
|
valid[i] = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Reference in New Issue
Block a user