=# # 139 Word Break
給一個String和一個List<String> dictionary,
回傳string是否可以由dictionary裡的字組成的
S = "LeetCode"
dic = [Leet, Code]
-> true
- Idea:
- O(N^2): dp+兩層for迴圈,一層指向substring的結尾,內層指向開頭,dp記錄該結尾是否valid
Pseudocode:
use boolean dp[] to record if each element can find a word in dict for loop through 1~length, indicate the end of substring for loop through 0~i, indicate the start of substring if dp[j] is true and wordDict contains substring(j,i), dp[i] = true; Test: "leetcode", {"leet", "code"} "", {"whatever"} "leetcode", {"leetcode"} "leetcode", {"l", "eetcode"} "leetcode", {"", "eetcode"} "leetcode", {"code"} "aaaaaaa", {"aaaa", "aaa"} strange punctuation
Code
public class Solution { public boolean wordBreak(String s, List<String> wordDict) { if(s.equals("")) return false; boolean dp[] = new boolean[s.length()+1]; dp[0] = true; for(int i=1; i<s.length()+1; i++){ for(int j=0; j<i; j++){ if(dp[j] && wordDict.contains(s.substring(j,i))){ dp[i] = true; break; } } } return dp[s.length()]; } }