mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
Merge pull request #1643 from zhicheng-lee/zhicheng-lee-patch-11
更新 0139.单词拆分.md Java代码
This commit is contained in:
@ -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;
|
||||
}
|
||||
}
|
||||
@ -248,6 +250,26 @@ class Solution {
|
||||
}
|
||||
}
|
||||
|
||||
// 另一种思路的背包算法
|
||||
class Solution {
|
||||
public boolean wordBreak(String s, List<String> wordDict) {
|
||||
boolean[] dp = new boolean[s.length() + 1];
|
||||
dp[0] = true;
|
||||
|
||||
for (int i = 1; i <= s.length(); i++) {
|
||||
for (String word : wordDict) {
|
||||
int len = word.length();
|
||||
if (i >= len && dp[i - len] && word.equals(s.substring(i - len, i))) {
|
||||
dp[i] = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return dp[s.length()];
|
||||
}
|
||||
}
|
||||
|
||||
// 回溯法+记忆化
|
||||
class Solution {
|
||||
private Set<String> set;
|
||||
@ -285,7 +307,7 @@ class Solution {
|
||||
|
||||
Python:
|
||||
|
||||
```python3
|
||||
```python
|
||||
class Solution:
|
||||
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
|
||||
'''排列'''
|
||||
|
Reference in New Issue
Block a user