Created
February 25, 2020 09:16
-
-
Save alldroll/5c0c79d1304469574162335cdf64fd7b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // https://leetcode.com/problems/word-break | |
| func wordBreak(s string, wordDict []string) bool { | |
| wordMap := make(map[string]struct{}, len(wordDict)) | |
| for _, word := range wordDict { | |
| wordMap[word] = struct{}{} | |
| } | |
| chars := []rune(s) | |
| n := len(chars) | |
| dp := make([]int, n + 1) | |
| dp[0] = 1 | |
| for i := 0; i < n && dp[n] == 0; i++ { | |
| if dp[i] == 0 { | |
| continue | |
| } | |
| for _, word := range wordDict { | |
| j := len(word) | |
| if i + j > n { | |
| continue | |
| } | |
| candidate := string(chars[i:i + j]) | |
| if _, ok := wordMap[candidate]; ok { | |
| dp[i + j] = 1 | |
| } | |
| } | |
| } | |
| return dp[n] == 1 | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment