Question
Have the function LongestWord(sen)
take the sen
parameter being passed and return the longest word in the string. If there are two or more words that are the same length, return the first word from the string with that length. Ignore punctuation and assume sen
will not be empty. Words may also contain numbers, for example "Hello world123 567".
Solution
const longestWordInArray = (sen) => {
if (sen.length === 0) {
return sen;
}
let idx = 0;
let len = 0;
const wordsArray = sen.replace(/[^\w ]/g, "").split(" ");
for (let i = 0; i < wordsArray.length; i++) {
if (wordsArray[i].length > len) {
len = wordsArray[i].length;
idx = i;
}
}
return wordsArray[idx];
};
console.log(longestWordInArray("fun&!! time chimpanze"));
Solution Breakdown
- The first step is to create the function called
longestWordInArray
. It takes one input called sen (which is just a string). - Next, we check if
sen
is empty (""). If it is we just return it. This prevents errors. - We set up two variables:
idx
, the position (index) of the longest word we find. At first, it’s 0.len
, the length of the longest word so far. At first, it’s 0.
const wordsArray = sen.replace(/[^\w ]/g, "").split(" ");
This line does two things:
-
sen.replace(/[^\w ]/g, "")
: removes punctuation and special characters, so we only keep letters, numbers, and spaces. Example: "fun&!! time" becomes "fun time". -
.split(" ")
: splits the sentence into an array of words (breaking at spaces). Example: "fun time chimpanze" becomes ["fun", "time", "chimpanze"].
So now we have an array of words.
for (let i = 0; i < wordsArray.length; i++) {
if (wordsArray[i].length > len) {
len = wordsArray[i].length;
idx = i;
}
}
This loop goes through each word in the array:
-
wordsArray[i]
: the current word. -
wordsArray[i].length
: the number of characters in that word.
If the length of the current word is greater than the current value of len
:
- Update
len
with the new length. - Update
idx
with the position of that word. This way, after the loop ends,idx
will point to the longest word.
Finally, we return the word at position idx
which is the longest word we found.
Conclusion.
In short, the function above removes punctuation, splits the sentence into words, checks which word is the longest, and returns it. The time and space complexity of the solution above is O(n).
Share your solutions in the comment below.
Top comments (0)