LeetCode 139 Word Break

LeetCode 139 Word Break

Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.

For example, givens = "leetcode",dict = ["leet", "code"].
Return true because "leetcode" can be segmented as "leet code".

上来直接用一个brute force,遍历字符串如果找到一个单词,继续recursion搜索剩余的字符串,果断超时。。。

参考了一下dp的思路。。。对于最优子结构的理解还是不够到位!!

这题的最优子结构在于:

假设字符串lookforthebestworld,用dp[]数组记录到某一位为止是否是validWords,则dp[0]-dp[3]都是false,dp[4]是true因为出现了第一个单词look!!!只有此时,才继续判断后续字符串forthebestworld。

代码:

public class Solution {
    public boolean wordBreak(String s, Set<String> wordDict) {
        int n = s.length();
        if (n == 0) return false;
        
        boolean[] valid = new boolean[n+1];
        valid[0] = true;
        
        for (int i = 1; i <= n; i++) {
            for (int j = 0; j < i; j++) {
                if (valid[j] && wordDict.contains(s.substring(j,i))) {
                    valid[i] = true;
                    break;
                }
            }
        }
        return valid[n];
    }
}

参考:
https://discuss.leetcode.com/topic/6156/java-implementation-using-dp-in-two-ways/3

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容