Basic Algorithm Scripting - Find the Longest Word in a String

Hi! I think I might have found an alternative solution to this problem. It’s kind of a stupid and inelegant solution but it doesn’t use any concepts that haven’t been introduced yet. It also doesn’t require the use of a regex. The only problem with it is that it doesn’t work on strings ending with some kind of punctuation, which is why a regex solution is probably better. It did work well enough to pass the challenge, but is it considered a valid solution, or just clever enough to pass the tests?

Edit: the console.log stuff is left over from when I was trying to figure out what was wrong with my code before I figured I could just add a space to the end of the string

My code:

function findLongestWordLength(str) {
  str += " " // I had to include this because otherwise it wouldn't get the last word
  let longest = 0 
  let current = 0 
  for (let i = 0; i < str.length; i++) {
    if (str[i] == " ") {
      if (current > longest) {
        longest = current; 
        console.log(longest)
      } 
    current = 0;
    } else {
      current++ 
    }
  } 
  return longest
}

findLongestWordLength("What if we try a super-long word such as otorhinolaryngology")
// findLongestWordLength("The quick brown fox jumped over the lazy dog");

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36

Challenge: Basic Algorithm Scripting - Find the Longest Word in a String

Link to the challenge:

There are several ways to solve this challenge. Yours is valid since it does what it is supposed to do. But yours is almost exactly like solution 1 in the hints, so I don’t think this would really be considered a new alternative solution to what is already offered.

I do think that a functional approach to this challenge is probably the more eloquent way to solve this. Take a look at solution 3 or solution 4.

Oh yeah you’re right lol the only thing I don’t understand about that solution is, why do the “current length” and “longest length” get compared twice in it?

What if the longest word is at the end of the string? The for loop ends when you reach the end of the string, so you won’t get to check if currentLength is greater than longestLength inside the for loop when you reach the end of the string. That’s why the check needs to be made one more time after the for loop is done. You worked around this by adding a space to the end of the string, so the for loop will go one past the real end of the string and thus you will make that check for the last word in the string.

Oh, that makes so much sense! I had so much trouble with that part; the adding a space thing was honestly kind of a desperation/frustration thing lol

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.