0%

leetcode 139 Solution

代码解析

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package com.demo.s139;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
* 单词拆分
* 给你一个字符串 s 和一个字符串列表 wordDict 作为字典。请你判断是否可以利用字典中出现的单词拼接出 s 。
*
* 注意:不要求字典中出现的单词全部都使用,并且字典中的单词可以重复使用。
*
* 来源:力扣(LeetCode)
* 链接:https://leetcode.cn/problems/word-break
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
public class Solution {

public boolean wordBreak(String s, List<String> wordDict) {
if(wordDict.size() == 0) return false;
Set<Integer> wordLength = new HashSet<>();
for (String word : wordDict) {
wordLength.add(word.length());
}
//单词去重
Set<String> dict = new HashSet<>(wordDict);
Set<String> wrongSet = new HashSet<>();
return matchWords(s, dict, wordLength, wrongSet);
}

public boolean matchWords(String s, Set<String> dict, Set<Integer> wordLength, Set<String> wrongSet) {
//特殊值判断
if("".equals(s) || dict.contains(s)) return true;
//遍历单词所有字符
for(Integer j : wordLength) {
if(j > s.length()) return false;
String sub = s.substring(0, j);
//截取字符串,找到单词表中存在的子串
if(dict.contains(sub)) {
String subEnd = s.substring(j);
if(!wrongSet.contains(subEnd) && matchWords(subEnd, dict, wordLength, wrongSet)) {
return true;
} else {
wrongSet.add(subEnd);
}
}
}
return false;
}
}