LeetCode 140. Word Break II

Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, add spaces in s to construct a sentence where each word is a valid dictionary word. You may assume the dictionary does not contain duplicate words.

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”].

UPDATE (2017/1/4):
The wordDict parameter had been changed to a list of strings (instead of a set of strings). Please reload the code definition to get the latest changes.

这一题和 139的区别就在于这一次要返回出所有可能性的组合

有了上一题的基础,思路也来得很快,就是在维护一个数组的同时维护一个map记录每一个点上的组合。
遍历可能性的时候将这些进行组合就可了。

可是代码提交时当例子为”aaaaaaabaaaaaaaaaaaaaaaaaaaaaaaa” [“a”,”aa”,”aaa” …..]的时候出现了超时,上网找了下,这应该想表达的是,应该是先判断字符串是否可切分,若可以再进行组合,否走不应该浪费时间在这些不可能切分的字符串上。

于是我就对字符串先进行了可切分判断,代码成功通过

 public List<String> wordBreak2(String s, List<String> wordDict) {
        Map<Integer, List<String>> map = new HashMap<Integer, List<String>>();
        List<String> firstList = new ArrayList<String>();
        firstList.add("");
        map.put(0, firstList);
        boolean d[] = new boolean[s.length() + 1];
        d[0] = true;
        for (int i = 1; i < d.length; i++) {
            for (int j = 0; j < i; j++) {
                if (d[j] && wordDict.contains(s.substring(j, i))) {
                    d[i] = true;
                    break;
                }
            }
        }
        //先预判是否可以拆分
        if (!d[s.length()]) return new ArrayList<String>();
        for (int i = 1; i < d.length; i++) {
            List<String> newList = new ArrayList<String>();
            if(d[i]) {
                for (int j = 0; j < i; j++) {
                    if (d[j] && wordDict.contains(s.substring(j, i))) {
                        d[i] = true;
                        List<String> oldList = map.get(j);
                        for (String str : oldList) {
                            newList.add((str + " " + s.substring(j, i)).trim());
                        }

                    }
                }
                    map.put(i, newList);

            }
        }

        return map.get(s.length())  == null ? new ArrayList<String>( ) : map.get(s.length());
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值