My Awesome Book

This file file serves as your book's preface, a great place to describe your book's content and ideas.

class Solution {
    public List<String> wordBreak(String s, List<String> wordDict) {
        List<String> res = new ArrayList<>();
        List<String> clist = new ArrayList<>();
        Set<String> set = new HashSet<>();
        helper(s, set, res, clist);
        return res;
    }

    private void helper(String s, Set<String> set, List<String> res, List<String> clist) {
        if(s.equals("")){
            res.add(convert(clist));
            return;
        }

        for(int i = 0; i < s.length(); i++) {
            String t = s.substring(0, i+1);
            if(set.contains(t)) {
                clist.add(t);
                helper(s.substring(i+1), set, res, clist);
                clist.remove(clist.size() - 1);
            }
        }
    }

    private String convert(List<String> clist) {
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < clist.size() - 1; i++) {
            sb.append(clist.get(i) + " ");
        }
        sb.append(clist.get(clist.size() - 1));
        return new String(sb);
    }
}

results matching ""

    No results matching ""