leetcode 139. 单词拆分

题解

动态规划,dp[i]表示字符串s的前i个字符是否可以拆分

示例代码(go)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
func wordBreak(s string, wordDict []string) bool {
n := len(s)
dp := make([]bool, n+1)
dp[0] = true
for i := 1; i <= n; i++ {
for j := 0; j < i; j++ {
if dp[j] && contains(s[j:i], wordDict) {
dp[i] = true
}
}
}
return dp[n]
}

func contains(s string, dict []string) bool {
for _, v := range dict {
if s == v {
return true
}
}
return false
}