DevPath

← All problems

Word Break

Medium dynamic-programming · strings

Description

Return true if the string can be segmented into a space-separated sequence of one or more words from the dictionary.

Constraints

1 <= length <= 300; dictionary words are lowercase

Examples

Input: s = "leetcode", words = ["leet","code"]

Output: true

Hints (1)
  • A reachable end index is anything reachable before it plus a dictionary word.

Solutions

Prefix reachability DP. · Time O(n^2) · Space O(n)

func wordBreak(s string, words []string) bool {
    set := map[string]bool{}
    for _, w := range words {
        set[w] = true
    }
    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] && set[s[j:i]] {
                dp[i] = true
                break
            }
        }
    }
    return dp[n]
}

Create a free account to submit solutions, track progress and save problems.

Create account