I'm trying to find the longest word in a given text, but it has to be done "old school": without using split, enumerate, etc. (I'm using Python but what I'm looking for is more of a pseudocode or a general algorithm). I'm struggling with the last word (or the last character).
As a precondition, there are no leading or trailing spaces.
So I came up with two options that do the job but I feel like they're breaking some best practices:
Option 1
longestWord=""
lenlongestWord=0
currentWord=""
for i in range(len(text)):
if text[i]==" " or i==len(text)-1:
if i==len(text)-1:
currentWord+=text[i]
if len(currentWord) > lenlongestWord:
longestWord=currentWord
lenlongestWord=len(currentWord)
currentWord=""
else:
currentWord+=text[i]
print("Longest word: ", longestWord)
From this one I dislike this part (but I had to do it or I would be missing the last word in the string:
if i==len(text)-1:
currentWord+=text[i]
because I'm duplicating the concatenation, both in the "if" block and the "else" block.
Option 2:
text+=" "
longestWord=""
lenlongestWord=0
currentWord=""
for i in range(len(text)):
if text[i]==" ":
if len(currentWord) > lenlongestWord:
longestWord=currentWord
lenlongestWord=len(currentWord)
currentWord=""
else:
currentWord+=text[i]
print("Longest word: ", longestWord)
What I don't like from this one is the fact that I'm manipulating the original text by adding a trailing whitespace so I can read it as a word separator.
Is there a third option I'm missing? Or maybe one of these two is not as bad practice as I believe?
currentWord
when the find a space, rather than when they mark something as longer