我正在处理这个问题。这似乎是我找到了正确的答案,并返回true,但然后它被错误覆盖..新手在Java中,对不起,如果它是一个虚拟的问题..我怎么才能返回true? 预先感谢您leetcode 139. Word Break
问题 给定一个字符串s和单词的字典dict,确定是否s时,可以分割成一个或多个字典单词空格分隔的序列。
例如,给定 s =“leetcode”, dict = [“leet”,“code”]。
返回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
莱特curIndex是4
curIndex是4
代码curIndex是8
1被称为..
2被称为..
2称为..
b为假
@BrandonIbbotson您可以点击刚才的图片,它会感谢被放大。 – success
@BrandonIbbotson我修正了它..谢谢你的建议。 – success