leetcode140单词拆分2

单词拆分II


给定一个非空字符串 s 和一个包含非空单词列表的字典 wordDict,在字符串中增加空格来构建一个句子,使得句子中所有的单词都在词典中。返回所有这些可能的句子。

说明:
分隔时可以重复使用字典中的单词。
你可以假设字典中没有重复的单词。

示例 1:
输入:
s = “catsanddog”
wordDict = [“cat”, “cats”, “and”, “sand”, “dog”]
输出:
[
“cats and dog”,
“cat sand dog”
]
示例 2:
输入:
s = “pineapplepenapple”
wordDict = [“apple”, “pen”, “applepen”, “pine”, “pineapple”]
输出:
[
“pine apple pen apple”,
“pineapple pen apple”,
“pine applepen apple”
]
解释: 注意你可以重复使用字典中的单词。

示例 3:
输入:
s = “catsandog”
wordDict = [“cats”, “dog”, “sand”, “and”, “cat”]
输出:
[]

dfs+备忘录

先看没有备忘录的版本,易于理解思路。

dfs无优化版本

dfs的思路是先查看当前到哪个字母了,然后去字典里面去找对应的,再继续进行下一次dfs。

class Solution {
    public List<String> wordBreak(String s, List<String> wordDict) {
        Collections.sort(wordDict, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return o1.compareTo(o2);
            }
        });
        res = dfs(0,s,wordDict,new String());
        return res;
    }
    private List<String> res = new LinkedList<>();
    private HashMap<Integer,List<String>> map = new HashMap<>();
    // index是本次需要查找的单词首字母,list是字典,apd是上次要加上的字符串
    // dfs返回值是list形式,表示以当前index为起点,这之后的字母可以构成的字符串都有哪些
    public List<String> dfs(int index,String s,List<String> list,String apd) {
        System.out.println("index = "+index+" apd = "+apd);
        List<String> back = new ArrayList<>();//back是返回值
        if (index == s.length()) {
        // 递归终止条件
            back.add(apd);
            return back;
        }
        char c = s.charAt(index);
        for (int i = 0; i < list.size(); i++) {
            String t = list.get(i);
            if (t.charAt(0) == c) {
                while (t.charAt(0) == c) {
                // 遍历所有以这个字母开头的字符串
                    if (index + t.length() <= s.length()) {
                        String origin = s.substring(index, index + t.length());
                        if (origin.equals(t)) {
                            List<String> tback = dfs(index + t.length(), s, list, t+" ");
                            back.addAll(tback);
                        }
                    }
                    i++;
                    if (i >= list.size()) {
                        break;
                    }
                    t = list.get(i);
                }
                break;
            }
        }
        for (int i = 0; i < back.size(); i++) {
            back.set(i,apd + back.get(i));
        }
        return back;
    }
}

但是这样遇到重复的字母"aaaaa",["a","aa","aaa"],会有很多次重复遍历后面的子串,所以可以用一个map把对应位置可以构成哪些字符串的情况存起来。

备忘录版本

public List<String> wordBreak(String s, List<String> wordDict) {
        Collections.sort(wordDict, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return o1.compareTo(o2);
            }
        });
        res = dfs(0,s,wordDict,new String());
        for (int i = 0; i < res.size(); i++) {
            res.set(i,res.get(i).trim());
        }
        //System.out.println(map);
        return res;
    }
    private List<String> res = new LinkedList<>();
    private HashMap<Integer,List<String>> map = new HashMap<>();
    public List<String> dfs(int index,String s,List<String> list,String apd) {
        //System.out.println("index = "+index+" apd = "+apd+" "+map);
        List<String> back = new ArrayList<>();
        List<String> l = null;
        if (index == s.length()) {
            back.add(apd);
            return back;
        }
        char c = s.charAt(index);
        boolean flag = false;
        //检查备忘录里面是否存在,即是否已经遍历过
        if (map.containsKey(index)) {
        //不能修改原来map里面已经存储的值,所以用l修改引用
        //没有这段话,下面for就会把当前index的value修改,因为是引用类型,都是同一份内存地址
            back = map.get(index);
            l = new ArrayList<>(back);
            map.put(index,l);
            for (int i = 0; i < back.size(); i++) {
                back.set(i,apd + back.get(i));
            }
            return back;
        }
        for (int i = 0; i < list.size(); i++) {
            String t = list.get(i);
            if (t.charAt(0) == c) {
                while (t.charAt(0) == c) {
                    //StringBuilder ap = new StringBuilder(sb);
                    if (index + t.length() <= s.length()) {
                        String origin = s.substring(index, index + t.length());
                        if (origin.equals(t)) {
                            List<String> tback = dfs(index + t.length(), s, list, t+" ");
                            back.addAll(tback);
                        }
                    }
                    i++;
                    if (i >= list.size()) {
                        break;
                    }
                    t = list.get(i);
                }
                break;
            }
        }
        // 处理方式同上面
        l = new ArrayList<>(back);
        map.put(index,l);
        for (int i = 0; i < back.size(); i++) {
            back.set(i,apd + back.get(i));
        }
        //System.out.println("index = "+index+" back = "+l+" "+map);
        return back;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值