Skip to content

Instantly share code, notes, and snippets.

@alldroll
Created February 25, 2020 09:16
Show Gist options
  • Select an option

  • Save alldroll/5c0c79d1304469574162335cdf64fd7b to your computer and use it in GitHub Desktop.

Select an option

Save alldroll/5c0c79d1304469574162335cdf64fd7b to your computer and use it in GitHub Desktop.
// 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