Problem Description
Given a string s consisting only of lowercase letters, find the length of the longest alphabetical continuous substring. An alphabetical continuous substring is a substring in which every subsequent character is the next letter in the English alphabet. For example, "abc" is valid, whereas "acb" or "za" are not.
Key Insights
- Iterate through the string while comparing each character with its previous character.
- If the current character is exactly one more than the previous (using their ASCII or ordinal representation), then it continues an alphabetical sequence.
- Reset the count when the sequence is broken.
- Keep track of the maximum sequence length encountered.
- The solution uses a single pass through the string, ensuring O(n) time complexity.
Space and Time Complexity
Time Complexity: O(n)
Space Complexity: O(1)
Solution
The approach involves iterating over the given string and maintaining a count of the current valid alphabetical sequence. For each character, we check if its ASCII value is exactly one more than that of its predecessor. If yes, we increase the current count. If not, we reset the count to 1. During the iteration, we update the result with the maximum count seen so far. This utilizes a simple linear scan and some constant extra space, making it both time and space efficient.