Length of the Longest Alphabetical Continuous Substring — LeetCode 2414 Python Solution
- Problem
- #2414
- Pattern
- Hash Map
- Reading time
- 2 min
- Source
- leetcode.com
The problem
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".
Example
- Input
- s = "abacaba"
- Output
- 2
- Explanation
- There are 4 distinct continuous substrings: "a", "b", "c" and "ab".
Python solution
class Solution:
def longestContinuousSubstring(self, s: str) -> int:
ans = cnt = 1
for x, y in pairwise(map(ord, s)):
if y - x == 1:
cnt += 1
ans = max(ans, cnt)
else:
cnt = 1
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the string s |
| Space | O(1) auxiliary |
Pattern: Hash Map
Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 2414. Length of the Longest Alphabetical Continuous Substring is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.
The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2414. Length of the Longest Alphabetical Continuous Substring?
- LeetCode 2414. Length of the Longest Alphabetical Continuous Substring is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2414. Length of the Longest Alphabetical Continuous Substring?
- The Python solution on this page runs in O(n), where n is the length of the string s.
- What is the space complexity of LeetCode 2414. Length of the Longest Alphabetical Continuous Substring?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 2414. Length of the Longest Alphabetical Continuous Substring cover?
- LeetCode 2414. Length of the Longest Alphabetical Continuous Substring is tagged String on LeetCode.