Length of the Longest Alphabetical Continuous Substring Problem
#2414
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2414.
An alphabetical continuous string is a string consisting of consecutive letters in the alphabet. In other words, it is any substring of the string "abcdefghijklmnopqrstuvwxyz".
- For example,
"abc"is an alphabetical continuous string, while"acb"and"za"are not.
Given a string s consisting of lowercase letters only, return the length of the longest alphabetical continuous substring.
Example 1:
Input: s = "abacaba"
Output: 2
Explanation: There are 4 distinct continuous substrings: "a", "b", "c" and "ab".
"ab" is the longest continuous substring.
Example 2:
Input: s = "abcde"
Output: 5
Explanation: "abcde" is the longest continuous substring.
Constraints:
1 <= s.length <= 10^5sconsists of only English lowercase letters.
Solution
Approach: Single Pass
Walk through s keeping cnt, the length of the alphabetical run ending at the current character, and ans, the best run so far; both start at 1. If s[i] - s[i - 1] == 1, extend the run (cnt += 1, ans = max(ans, cnt)). Otherwise restart with cnt = 1.
Complexity: O(n) time and O(1) extra space.
class Solution:
def longestContinuousSubstring(self, s: str) -> int:
ans = cnt = 1
for i in range(1, len(s)):
if ord(s[i]) - ord(s[i - 1]) == 1:
cnt += 1
ans = max(ans, cnt)
else:
cnt = 1
return ans