Note: study again. DP.
(s string, wordDict []string)
| 2 | |
| 3 | // Note: study again. DP. |
| 4 | func wordBreak(s string, wordDict []string) bool { |
| 5 | // create a set of words in wordDict for fast lookup |
| 6 | wordDictSet := make(map[string]bool) |
| 7 | for _, w := range wordDict { |
| 8 | wordDictSet[w] = true |
| 9 | } |
| 10 | |
| 11 | // create a dp array which stores whether the i-th |
| 12 | dp := make([]bool, len(s)+1) |
| 13 | dp[0] = true |
| 14 | |
| 15 | // i represents the length of the current substring bring considered |
| 16 | for i := 1; i <= len(s); i++ { |
| 17 | // j represents the location of the partition in s[0:i] |
| 18 | for j := 0; j < i; j++ { |
| 19 | |
| 20 | // if the partition up to j is in the wordDict |
| 21 | // and the s[j:i] is in the wordDict, then set |
| 22 | // dp[i] = true. |
| 23 | partition1 := dp[j] |
| 24 | partition2 := s[j:i] |
| 25 | if partition1 && wordDictSet[partition2] { |
| 26 | dp[i] = true |
| 27 | break |
| 28 | } |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | return dp[len(dp)-1] |
| 33 | } |
| 34 | |
| 35 | // Recursive solution, which exceeds the time limit. |
| 36 | func wordBreak0(s string, wordDict []string) bool { |
no outgoing calls