2414.最长的字母序连续子字符串的长度

目标

字母序连续字符串 是由字母表中连续字母组成的字符串。换句话说,字符串 "abcdefghijklmnopqrstuvwxyz" 的任意子字符串都是 字母序连续字符串 。

  • 例如,"abc" 是一个字母序连续字符串,而 "acb" 和 "za" 不是。

给你一个仅由小写英文字母组成的字符串 s ,返回其 最长 的 字母序连续子字符串 的长度。

示例 1:

输入:s = "abacaba"
输出:2
解释:共有 4 个不同的字母序连续子字符串 "a"、"b"、"c" 和 "ab" 。
"ab" 是最长的字母序连续子字符串。

示例 2:

输入:s = "abcde"
输出:5
解释:"abcde" 是最长的字母序连续子字符串。

说明:

  • 1 <= s.length <= 10^5
  • s 由小写英文字母组成

思路

首先要明确 字母序连续 的含义, abc 是字母序连续,abd abccd 是不是字母序连续?不是。

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".

字母序连续字符串是由字母表中连续的字母组成的字符串,即 abcdefghijklmnopqrstuvwxyz 的任意子字符串。

有一个由小写英文字母组成的字符串,求它的字母序连续子串的最大长度。显然,最大长度不会超过26。只需要一次遍历,如果不是字母序连续则重新计数,取最大值即可。

代码


/**
 * @date 2024-09-19 13:48
 */
public class LongestContinuousSubstring2414 {

    public int longestContinuousSubstring(String s) {
        int n = s.length();
        int res = 0;
        int cnt = 0;
        int last = s.charAt(0) - 1;
        for (int i = 0; i < n; i++) {
            char c = s.charAt(i);
            if (c - last == 1) {
                res = Math.max(res, ++cnt);
            } else {
                cnt = 1;
            }
            last = c;
        }
        return res;
    }

}

性能