[Word Break II] Why I cannot pass the test case "a" ["a"]??


  • 0
    H
    public ArrayList<String> wordBreak(String s, Set<String> dict) {
        ArrayList<ArrayList<String>> result = new ArrayList<ArrayList<String>>();
        ArrayList<String> sentence = new ArrayList<String>();
        dfs(s, 0, dict, sentence, result); // call dfs recursively
        ArrayList<String> resultset = new ArrayList<String>();
        for (int i = 0; i < result.size(); i++) {
            String s1 = new String("");
            for (int j = 0; j < result.get(i).size(); j++) {
                if (j != result.get(i).size()-1) {
                    s1 += result.get(i).get(j)+" ";
                } else {
                    s1 += result.get(i).get(j);
                }
            }
            resultset.add(s1);
        }
        return resultset;
    }
    // DFS+backtracing
    public void dfs(String s, int nextIndex, Set<String> dict, ArrayList<String> sentence, ArrayList<ArrayList<String>> result) {
        if (nextIndex == s.length()) { // reach the end correctly
            result.add(new ArrayList<String>(sentence));
            return;
        }
        // traversal the word dict and apply DFS
        for (String word : dict) {
            int len = word.length();
            if (nextIndex+len <= s.length() && word == s.substring(nextIndex, nextIndex+len)) {
                sentence.add(word);
                dfs(s, nextIndex+len, dict, sentence, result);
                sentence.remove(sentence.size()-1);
            }
        }
        return;
    }
    

    Can anyone paste/test it and help me to debug it??


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.