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<String> wordBreak(String s, HashSet<String> set) {
    List<String> ret = new ArrayList<String>();
    helper(s, set, ret);
    return ret;
}

private boolean helper(String s, Set<String> set, List<String> 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

    原文作者:Richardo92
    原文地址: https://www.jianshu.com/p/6fdc84526457#comments
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞