2414. Length of the Longest Alphabetical Continuous Substring
https://leetcode.com/problems/length-of-the-longest-alphabetical-continuous-substring/description/
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 <= 105
s
consists of only English lowercase letters.
----
Intuition
Two pointers
if (lo == hi || charAt(hi) - charAt(lo) == 1)
hi++;
ans = max(ans, hi - lo) ---> hi - lo = length after increment
else
lo = hi --- restart a new substring
---
Time - O(N)
Space - O(1)
---
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public int longestContinuousSubstring(String s) { | |
int hi = 0, lo = 0, ans = 1; | |
while (hi < s.length()) { | |
if (hi == lo || s.charAt(hi) - s.charAt(hi - 1) == 1) { | |
hi++; | |
ans = Math.max(ans, hi - lo); | |
} else { | |
lo = hi; | |
} | |
} | |
return ans; | |
} | |
} |