You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
When a string and a word dictionary are given, find a string can be completed by composition of words in dictionary.
Same word can be used more than once.
Approach
Using brute force, we can inspect about the every substrings.
The code is below.
Using dp, we can solve this faster.
When s is "leetcode" and dictionary is ["leet", "code"],
dp[8] is true, because index 8 is the last index of the string.
dp[7] is false, because 'e' is not in the dictionary.
dp[6] is false, because 'de' is not in the dictionary.
dp[5] is false, because 'ode' is not in the dictionary.
dp[4] is true, because 'code' is in the dictionary.
dp[3] is false, because 't' is not in the dictionary.
dp[2] is false, because 'et' is not in the dictionary.
dp[1] is false, because 'eet' is not in the dictionary.
dp[0] is true, because 'leet' is in the dictionary.
Problem
When a string and a word dictionary are given, find a string can be completed by composition of words in dictionary.
Same word can be used more than once.
Approach
Using brute force, we can inspect about the every substrings.
The code is below.
But this solution has a high time complexity.
Better solution
Using dp, we can solve this faster.
When s is "leetcode" and dictionary is ["leet", "code"],
dp[8] is true, because index 8 is the last index of the string.
dp[7] is false, because 'e' is not in the dictionary.
dp[6] is false, because 'de' is not in the dictionary.
dp[5] is false, because 'ode' is not in the dictionary.
dp[4] is true, because 'code' is in the dictionary.
dp[3] is false, because 't' is not in the dictionary.
dp[2] is false, because 'et' is not in the dictionary.
dp[1] is false, because 'eet' is not in the dictionary.
dp[0] is true, because 'leet' is in the dictionary.
The code is below.
The text was updated successfully, but these errors were encountered: