Problem Description
There is a given string s
and an array of strings dictionary
. You need to check if the words
obtained by splitting the string s
by spaces exist in the dictionary
.
If all the words in s
exist in the dictionary
, return true
; otherwise,
return false
.
Examples
Example 1
Input: s = “apple banana”, dictionary = [“apple”, “sweet potato”, “banana”]
Output: true
Example 2
Input: s = “orange grape”, dictionary = [“apple”, “banana”]
Output: false
Solution
To solve this problem, the following steps are necessary:
- Split the string
s
by spaces to create a list of words. - Check if all words in the list are included in the
dictionary
. - If all words are included, return
true
; if any word is not included, return
false
.
Implementation
Based on this logic, let’s write the JavaScript code:
function isAllWordsInDictionary(s, dictionary) {
const words = s.split(" "); // Split words by spaces
const dictionarySet = new Set(dictionary); // Convert to Set for optimized search
for (const word of words) {
if (!dictionarySet.has(word)) { // Check if each word is in the dictionary
return false; // Return false if any word is not found
}
}
return true; // Return true if all words are found
}
// Example tests
console.log(isAllWordsInDictionary("apple banana", ["apple", "sweet potato", "banana"])); // true
console.log(isAllWordsInDictionary("orange grape", ["apple", "banana"])); // false
Code Explanation
In the code above, we perform the following steps:
s.split(" ")
: Splits the given strings
by spaces to create a list of words.new Set(dictionary)
: Converts the givendictionary
array to a Set to remove duplicates and optimize
search times to O(1).- We use a for loop to check if each word exists in the
dictionarySet
. - If a word does not exist,
false
is returned; if all words exist,true
is returned.
Time Complexity
The time complexity of this algorithm is O(n + m), where n
is the number of words in the string s
and
m
is the number of words in the dictionary
. The reason for using a Set is to improve the search speed to enhance
overall performance.
Conclusion
This problem allowed us to effectively use strings and arrays to verify whether the given conditions were met.
When solving algorithm problems, it is always easier to approach them by breaking them down into steps.
Such problems can also be beneficially utilized in other scenarios.