美文网首页计算机
Interview Question - Word break

Interview Question - Word break

作者: Richardo92 | 来源:发表于2016-09-28 07:25 被阅读9次

    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

    相关文章

      网友评论

        本文标题:Interview Question - Word break

        本文链接:https://www.haomeiwen.com/subject/boshyttx.html