Skip to content

2414. Length of the Longest Alphabetical Continuous Substring 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
 public:
  int longestContinuousSubstring(string s) {
    int ans = 1;
    int runningLen = 1;

    for (int i = 1; i < s.length(); ++i)
      if (s[i] == s[i - 1] + 1)
        ans = max(ans, ++runningLen);
      else
        runningLen = 1;

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
  public int longestContinuousSubstring(String s) {
    int ans = 1;
    int runningLen = 1;

    for (int i = 1; i < s.length(); ++i)
      if (s.charAt(i) == s.charAt(i - 1) + 1)
        ans = Math.max(ans, ++runningLen);
      else
        runningLen = 1;

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution:
  def longestContinuousSubstring(self, s: str) -> int:
    ans = 1
    runningLen = 1

    for a, b in zip(s, s[1:]):
      if ord(a) + 1 == ord(b):
        runningLen += 1
        ans = max(ans, runningLen)
      else:
        runningLen = 1

    return ans