每天一道算法题(七)Leetcode – Word BreakII (Java)

题目:
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”],
* the solution is [“cats and dog”, “cat sand dog”].


本题没有想出使用dfs的做法,所以找了一下解法。
思路:核心是字符串中的单词和字典项比较
1.本题使用了dp和dfs两种算法
2.根据题意,背包中不在放flag,而是存放和题意相符的单词
3.利用dfs递归算法取得所有结果


代码:

public static List<String> wordBreak(String s, Set<String> dict) {

        List<String>[] dp = new List[s.length() + 1];
        dp[0] = new ArrayList();

        for (int i = 0 ; i < s.length() ; i++) {
            if (dp[i] == null) {
                continue;
            }

            for (String word : dict) {
                int len = word.length();
                int end = i + len;
                if(end > s.length()) 
                    continue;

                if (s.substring(i , end).equals(word)) {
                    if (dp[end] == null) {
                        dp[end] = new ArrayList();
                    }
                    dp[end].add(word);
                }
            }
        }

        List<String> result = new ArrayList<String>();
        if (dp[s.length()] == null) {
            return result;
        }
        List<String> temp = new ArrayList<String>();
        dfs(dp, s.length(), result, temp);

        return result;
    }

    /**
     * 递归解法,需要有一个终止条件
     * 此问题的终止条件是end <= 0
     * @param dp
     * @param end
     * @param result
     * @param tmp
     */
    public static void dfs(List<String> dp[],int end,List<String> result, List<String> tmp){
        if (end <= 0) {
            String path = tmp.get(tmp.size() - 1);
            for (int i=tmp.size()-2; i>=0; i--) {
                path += " " + tmp.get(i);
            }
            result.add(path);
            return;
        }
        for (String word : dp[end]) {
            tmp.add(word);
            dfs(dp, end - word.length(), result, tmp);
            tmp.remove(tmp.size() - 1);
        }
    }
    @Test
    public static void main(String[] args){
        String str = "catsanddog";
        String[] strs = {"cat", "cats", "and", "sand", "dog"};  
        Set<String> dict = new HashSet<String>(Arrays.asList(strs));  
        System.out.println(wordBreak(str, dict));
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值