InferenceAI

Enter at least two characters to search.

Start free

Segment Into Words

mediumDynamic Programming25 min25 XP

Return True if s can be split into a sequence of one or more words from words (words may be reused).

Examples

EXAMPLE WALKTHROUGHtwo words

A guided view of the published example, not a trace of your code.

INPUT["leetcode",["leet","code"]]
TASKsegment_into_words()
EXPECTED OUTPUTtrue

Start with the input values shown in this example.

Example 1 of 3

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

Output: true

Explanation: two words

Input: s = "applepenapple", words = ["apple","pen"]

Output: true

Explanation: reused word

Input: s = "catsandog", words = ["cats","dog","sand","and","cat"]

Output: false

Explanation: impossible

Hint 1

ok[i] is True when the prefix of length i can be segmented.

Hint 2

ok[i] = any(ok[j] and s[j:i] in words).

Topics

DSADynamic ProgrammingPython