Skip to content

Longest Word

Define a word as a sequence of consecutive English letters. Find the longest word from the given string.

Example

For text = "Ready, steady, go!", the output should be

longest_word(text) = "steady"

Solution

py
def longest_word(text):
    max_word, word = '', ''

    for char in text:
        if char.isalpha():
            word += char
        else:
            max_word = max(word, max_word, key=len)
            word = ''

    return max(word, max_word, key=len)


print(longest_word("abcd"))
js
function longestWord(text) {
  let maxWord = '';
  let word = '';

  for (let char of text) {
    if (char.match(/[a-zA-Z]/)) {
      word += char;
    } else {
      maxWord = word.length > maxWord.length ? word : maxWord;
      word = '';
    }
  }

  return word.length > maxWord.length ? word : maxWord;
}

console.log(longestWord('Ready, steady, go!'));

my thoughts are neither my employer's nor my wife's