WordBreak checks if the input string can be segmented into words from a dictionary
(s string, wordDict []string)
| 8 | |
| 9 | // WordBreak checks if the input string can be segmented into words from a dictionary |
| 10 | func WordBreak(s string, wordDict []string) bool { |
| 11 | wordSet := make(map[string]bool) |
| 12 | for _, word := range wordDict { |
| 13 | wordSet[word] = true |
| 14 | } |
| 15 | |
| 16 | dp := make([]bool, len(s)+1) |
| 17 | dp[0] = true |
| 18 | |
| 19 | for i := 1; i <= len(s); i++ { |
| 20 | for j := 0; j < i; j++ { |
| 21 | if dp[j] && wordSet[s[j:i]] { |
| 22 | dp[i] = true |
| 23 | break |
| 24 | } |
| 25 | } |
| 26 | } |
| 27 | return dp[len(s)] |
| 28 | } |
no outgoing calls