WordBreak1

题目地址:https://leetcode.com/problems/word-break/#/description

题目:
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. You may assume the dictionary does not contain duplicate words.
For example, given s = "leetcode"dict = ["leet", "code"].
Return true because "leetcode" can be segmented as "leet code".

思路:
这道题看似可以直接用twopointer来解决,但是对于s = aaaaaaa, word是aaa和aaaa是会有问题的。所以这题只能够用dynamic programming来解决。但是中间会用到twopointer的思想。

代码:

public boolean wordBreak(String s, List<String> wordDict) {
    if(s == null || s.length() == 0){
        return false;
    }
    boolean[] valid = new boolean[s.length() + 1];
    valid[0] = true;
    for(int fast = 1; fast <= s.length(); fast++){
        for(int slow = 0; slow <= fast - 1; slow++){
            if(wordDict.contains(s.substring(slow, fast)) && valid[slow]){
                valid[fast] = true;
                break;
            }
        }
    }
    return valid[s.length()];
}

Comments

Popular Posts