139. Word Break

Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words.

Note:

The same word in the dictionary may be reused multiple times in the segmentation.
You may assume the dictionary does not contain duplicate words.
Example 1:

Input: s = "leetcode", wordDict = ["leet", "code"]
Output: true
Explanation: Return true because "leetcode" can be segmented as "leet code".
Example 2:

Input: s = "applepenapple", wordDict = ["apple", "pen"]
Output: true
Explanation: Return true because "applepenapple" can be segmented as "apple pen apple".
             Note that you are allowed to reuse a dictionary word.
Example 3:

Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
Output: false

本题使用动态规划的方法可以轻松解决。

public boolean wordBreak(String s, List<String> wordDict) {
        boolean[] dp = new boolean[s.length() + 1];//dp[i]代表s.subString(0, i)可以使用wordDict里面的词分割
        dp[0] = true;//设置初始条件;s.subString(0, 0)当然满足要求
        for(int i = 1; i <= s.length(); ++i) {//依次判断dp[i]的分割序列是否分别存在于wordDict里面
            for(int j = 0; j < i; ++j) {
                if(dp[j] && wordDict.contains(s.substring(j, i))) {//dp[j]的分割序列和s.substring(j, i)都存在于wordDict里面
                    dp[i] = true;
                    break;
                }
            }
        }
        return dp[s.length()];
    }

PS:做了140. Word Break II之后,发现还可以使用DFS的方法来解答。

public boolean wordBreak(String s, List<String> wordDict) {
        Map<String, Boolean> map = new HashMap<>();//dp.get(s)表示s的分割集是否都存在于wordDict里
        map.put("", true);//初始化
        return DFS(s, wordDict, map);
    }

    private boolean DFS(String s, List<String> wordDict, Map<String, Boolean> map) {
        if(map.containsKey(s)) {
            return map.get(s);
        }
        for(int i = 0; i < wordDict.size(); ++i) {
            String word = wordDict.get(i);
            if(s.startsWith(word) && DFS(s.substring(word.length()), wordDict, map)) {
                map.put(s, true);
                return true;
            }
        }
        map.put(s, false);
        return false;
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值