2016-09-07 54 views
0

我正在处理这个问题。这似乎是我找到了正确的答案,并返回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为假

+0

@BrandonIbbotson您可以点击刚才的图片,它会感谢被放大。 – success

+1

@BrandonIbbotson我修正了它..谢谢你的建议。 – success

回答

0

这可能不是回答你的问题,但我刚才提到的方法,并且绝非我是说,我的方法是更好还是更优化。

在您的代码中,没有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

+0

感谢您的解决方案,但如果我能知道我的代码中存在什么问题,它可能会更有帮助。谢谢你。 – success

+0

当然!我刚刚更新了我的答案。 –

+0

我实际上有“返回true”声明,但它被“return false”覆盖 – success