0
点赞
收藏
分享

微信扫一扫

【LeeCode】139. 单词拆分

半秋L 2023-01-04 阅读 67

【题目描述】

给你一个整数数组 ​​nums​​ ,请你找出一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。

子数组 是数组中的一个连续部分。

 ​​https://leetcode.cn/problems/word-break/?favorite=2cktkvj​​

【示例】

【LeeCode】139. 单词拆分_List

【代码】​​宫水三叶​​

​​其他​​

class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
Set<String> set = new HashSet<>();
for (String word : wordDict) set.add(word);
int n = s.length();
boolean[] f = new boolean[n + 10];
f[0] = true;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i && !f[i]; j++) {
String sub = s.substring(j - 1, i);
if (set.contains(sub)) f[i] = f[j - 1];
}
}
return f[n];
}
}

【代码】admin

通过率  35/45 ; 这里有个问题就是  “aaa”, "aaaa" 在判断的时候第一次aaa就返回了, 导致第二次判断有问题

另: 这里可以学习一下 list的初始化

package com.company;
// 2023-1-4
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
// 这里的s是动态变化的,所以长度大小也是直接判断就好
for (int i = 0; i <= s.length(); i++){
String tmp = s.substring(0, i);
if (wordDict.contains(tmp)){
int start = s.indexOf(tmp);
int end = start + tmp.length();
s = s.substring(0, start) + s.substring(end);
if (s.length() == 0) return true;
i = end - start - i;
}
}
return false;
}
}
public class Test {
public static void main(String[] args) {
new Solution().wordBreak("aaaaaaa", Arrays.asList("aaaa", "aaa")); // 输出: true, 本例输出有误
new Solution().wordBreak("leetcode", Arrays.asList("leet", "code")); // 输出: true
new Solution().wordBreak("applepenapple", Arrays.asList("apple", "pen")); // 输出: true
new Solution().wordBreak("catsandog", new ArrayList<>(){{ add("cats"); add("dog"); add("sand"); add("and"); add("cat"); }}); // 输出: false

}
}

通过率: 34/45 , 换了个思路, 以wordDict为根, 然后依次便利s中的字符串, 有则删除无则继续  还是有问题

class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
for (int i = 0; i < wordDict.size(); i++){
String x = wordDict.get(i);
int start = s.indexOf(x);
if (start != -1){
int end = start + x.length();
s = s.substring(0, start) + s.substring(end);
if (s.length() == 0) {
System.out.println(true);
return true;
}
i = i - 1;
}
}
System.out.println(false);
return false;
}
}
public class Test {
public static void main(String[] args) {
new Solution().wordBreak("aaaaaaa", Arrays.asList("aaaa", "aaa")); // 输出: true
new Solution().wordBreak("cars", Arrays.asList("car", "ca", "rs")); // 输出: true 本例有误
new Solution().wordBreak("leetcode", Arrays.asList("leet", "code")); // 输出: true
new Solution().wordBreak("applepenapple", Arrays.asList("apple", "pen")); // 输出: true
new Solution().wordBreak("catsandog", new ArrayList<>(){{ add("cats"); add("dog"); add("sand"); add("and"); add("cat"); }}); // 输出: false
}
}

举报

相关推荐

0 条评论