Word Break II

来源:互联网 发布:游戏编程directx9.0 编辑:程序博客网 时间:2024/06/04 19:12

Q:

Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word.

Return all such possible sentences.

For example, given
s = "catsanddog",
dict = ["cat", "cats", "and", "sand", "dog"].

A solution is ["cats and dog", "cat sand dog"].


Solution:

A brute force solution:

public class Solution {    public List<String> wordBreak(String s, Set<String> dict) {        List<String> list = new ArrayList<String>();        addSpace(s, "", 0, dict, list);        return list;    }        void addSpace(String s, String added, int index, Set<String> dict, List<String> list) {        if (index == s.length()) {            list.add(added);            return;        }        for (int i = index; i < s.length(); i++) {            if (dict.contains(s.substring(index, i+1))) {                added = added + s.substring(index, i+1) + " ";                addSpace(s, added, i+1, dict, list);            }        }    }}

a solution passed on leetcode:

public class Solution {    Map<String, List<String> > map = new HashMap<String, List<String> >();    public List<String> wordBreak(String s, Set<String> dict) {        List<String> list = new ArrayList<String>();        if (map.containsKey(s))            return map.get(s);        for (int i = 1; i <= s.length(); i++) {            String left = s.substring(0, i);            String right = s.substring(i, s.length());            if (dict.contains(left)) {                List<String> newlist = wordBreak(right, dict);                for (String str: newlist)                    list.add(left + " " + str);                if (right.length() == 0)                    list.add(left);            }        }        map.put(s, list);        return list;    }}


0 0