LeetCode 139. Word Break 字符串 DP

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”.

題目鏈接

題目描述
給定一個單詞s,和字典dict,看是否可以通過dict中的單詞拼接出來。
思路
這個題目錯了好多遍。使用dp[i]代表從s[i]到末尾能否用dict中的單詞表示,這就註定我們要尾部來遍歷。


public class WordBreak {
    public boolean wordBreak(String s, Set<String> dict) {
        boolean[] dp = new boolean[s.length()+1]; 
        Arrays.fill(dp, false);
        dp[s.length()] = true; 
        for ( int i=s.length()-1; i>=0; i-- ) { //!!
            for ( int j=s.length()-1; j>=i; j-- ) {
                String t = s.substring(i, j+1); 
                if ( dict.contains(t) && dp[j+1] ) {
                    dp[i] = true ; 
                    break; 
                }
            }
        }
        return dp[0]; 
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章