gpt4 book ai didi

java - leetcode 139. 分词

转载 作者:行者123 更新时间:2023-12-01 09:31:17 27 4
gpt4 key购买 nike

我正在研究这个问题。似乎我找到了正确的答案并返回 true,但随后它被 false 覆盖。Java 新手,抱歉,如果这是一个虚拟问题。我如何返回 true?预先感谢您

问题给定一个字符串 s 和一本单词字典 dict,确定 s 是否可以分割成一个或多个字典单词的空格分隔序列。

例如,给定s = "力特代码",dict = [“leet”,“代码”]。

返回 true,因为“leetcode”可以分段为“leet code”。

import java.util.HashSet;
import java.util.Set;
public class Hi {

public static void main(String[] args) {
String str = "leetcode";
Set<String> set = new HashSet<String>();
set.add("leet");
set.add("code");
boolean b = wordBreak(str, set);
System.out.println("b is " + b);
}

public static boolean wordBreak(String s, Set<String> wordDict) {
if(s.length() == 0 || wordDict.isEmpty()) {
return false;
}
return helper(s, wordDict, 0);
}

public static boolean helper(String s, Set<String> wordDict, int index) {
if(index == s.length()) {
System.out.println("1 is called.. ");
return true;
}
int curIndex = index;
System.out.println("curIndex is " + curIndex);
while(index < s.length()) {
//System.out.println("s.length() is " + s.length());
curIndex++;
if(curIndex > s.length()) {
System.out.println("2 is called.. ");
//return false;
return false;
}
if(wordDict.contains(s.substring(index, curIndex))) {
System.out.println(s.substring(index, curIndex) + " curIndex is " + curIndex);
helper(s, wordDict, curIndex);
}
}
System.out.println("3 is called.. ");
return false;
}

输出:curIndex 为 0

leet curIndex 为 4

curIndex 为 4

代码 curIndex 为 8

1 被称为..

2 被称为..

2 被称为..

b 为假

最佳答案

这可能无法回答您的问题,但我只是提到了一种方法,绝不是说我的方法更好或更优化。

在您的代码中,没有 return true 语句。该代码执行正确的工作,但在最后,由于循环不会在任何地方中断,因此它总是返回 false。我的意思是,您需要根据某些条件以及我在下面的示例中提到的此类条件之一在某处返回 true。

private static boolean test(String str, Set<String> set) {
int i = 1;
int start = 0;
List<String> tokens = new ArrayList<String>();

while (i <= str.length()) {
String substring = str.substring(start, i);
if (set.contains(substring)) {
tokens.add(substring);
start = substring.length();
}
i++;
}

String abc = "";
for (String a : tokens) {
abc = abc + a;
}

System.out.println(abc);

if (abc.equals(str)) {
return true;
} else {
return false;
}
}

下面是调试器内调试跟踪的屏幕截图。

enter image description here

关于java - leetcode 139. 分词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39380031/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com