Comparing neighbours
Compare each letter with the one before it, and stop at the first surprise. About 9 minutes.
Letters have an order
Letters line up in the order of the alphabet, as in a dictionary. So you can ask which of two letters comes first. The letter b comes after a, and c comes after b. You can compare letters with less than and greater than, just like numbers.
A word is in alphabetical order when no letter comes before the one in front of it. "abbey" is in order, but "abca" is not, because the last a comes before the c.
"a" < "b" # True "c" < "b" # False
Check each pair of neighbours
To check a whole word, look at each letter and the one just before it. Start from the second letter, because the first has nobody in front of it. If a letter comes before its neighbour, the word is out of order, and you can say no right away.
If you get to the end without finding a problem, the answer is yes. A word of one letter, or no letters, is in order, because there is nothing to compare.
for i in range(1, len(s)):
if s[i] < s[i - 1]:
return False
return True- now
- b
- before
- a
Compare b with the letter before it, a. b doesn't come before a, so that's fine.
Is the word "abbey" in alphabetical order, where a repeated letter is fine?
- AYes
- BNo, because b is repeated
- CNo, because it ends in y
Show the answer
Yes. a, b, b, e, y: no letter comes before the one in front of it.
Is it in order?
Return true if the letters of the word are in alphabetical order, where a repeated letter is fine (each letter is the same as or after the one before it). Words of 0 or 1 letters are in order.
s = "abbey" → true
0 ≤ length of s ≤ 1,000 · lowercase letters only