Interview Question - Word break I, find one matched List

Word Break, 只要找到一个valid的解就可以了

http://www.1point3acres.com/bbs/forum.php?mod=viewthread&tid=176097&highlight=snapchat

My code:

public List wordBreak(String s, HashSet set) {
    List ret = new ArrayList();
    helper(s, set, ret);
    return ret;
}

private boolean helper(String s, Set set, List ret) {
    if (s.length() == 0) {
        return true;
    }
    for (String word : set) {
        if (s.startsWith(word)) {
            ret.add(word);
            boolean flag = helper(s.substring(word.length()), set, ret);
            if (flag) {
                return true;
            }
            ret.remove(ret.size() - 1);
        }
    }
    return false;
}

Anyway, Good luck, Richardo! -- 09/27/2016

你可能感兴趣的:(Interview Question - Word break I, find one matched List)