Input: s = "ilike", dictionary[] = ["i", "like", "sam", "sung", "samsung", "mobile", "ice", "cream", "icecream", "man", "go", "mango"]
Output: "Yes"
Explanation: The string "ilike"
can be segmented into "i like"
, which consists of valid words "i"
and "like"
from the dictionary.
Input: s = "ilikesamsung", dictionary[] = ["i", "like", "sam", "sung", "samsung", "mobile", "ice", "cream", "icecream", "man", "go", "mango"]
Output: "Yes"
Explanation: The string can be segmented as "i like samsung" or "i like samsung"
A Trie can efficiently store dictionary words and enable fast prefix matching. Each node represents a character, allowing quick checks for the existence of a prefix. By recursively trying all possible prefixes of a string, we can check if each prefix exists in the Trie. If a prefix is found, we then check if the remaining substring is also segmentable. This approach eliminates redundant checks and speeds up the process of determining if the string is segmentable.