LeetCode 2414.最长的字母序连续子字符串的长度:一次遍历

【LetMeFly】2414.最长的字母序连续子字符串的长度:一次遍历

力扣题目链接:https://leetcode.cn/problems/length-of-the-longest-alphabetical-continuous-substring/

字母序连续字符串 是由字母表中连续字母组成的字符串。换句话说,字符串 "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 由小写英文字母组成

解题方法:一次遍历

使用一个变量nowCnt记录当前"连续字符串"的长度,使用一个变量ans记录最终答案。

从第二个元素开始遍历字符串,若当前元素是上一个元素的"下一个字母",则nowCnt加一,更新ans;否则将nowCnt重制为1。

  • 时间复杂度 O ( l e n ( s ) ) O(len(s)) O(len(s))
  • 空间复杂度 O ( 1 ) O(1) O(1)

AC代码

C++
cpp 复制代码
class Solution {
public:
    int longestContinuousSubstring(string s) {
        int ans = 1, nowCnt = 1;
        for (int i = 1; i < s.size(); i++) {
            if (s[i] == s[i - 1] + 1) {
                nowCnt++;
                ans = max(ans, nowCnt);
            }
            else {
                nowCnt = 1;
            }
        }
        return ans;
    }
};
Go
go 复制代码
package main

func longestContinuousSubstring(s string) int {
    ans, nowCnt := 1, 1
    for i := 1; i < len(s); i++ {
        if s[i] == s[i - 1] + 1 {
            nowCnt++
            if nowCnt > ans {
                ans = nowCnt
            }
        } else {
            nowCnt = 1
        }
    }
    return ans
}
Java
java 复制代码
class Solution {
    public int longestContinuousSubstring(String s) {
        int ans = 1, nowCnt = 1;
        for (int i = 1; i < s.length(); i++) {
            if (s.charAt(i) == s.charAt(i - 1) + 1) {
                nowCnt++;
                ans = Math.max(ans, nowCnt);
            }
            else {
                nowCnt = 1;
            }
        }
        return ans;
    }
}
Python
python 复制代码
class Solution:
    def longestContinuousSubstring(self, s: str) -> int:
        nowCnt, ans = 1, 1
        for i in range(1, len(s)):
            if ord(s[i]) == ord(s[i - 1]) + 1:
                nowCnt += 1
                ans = max(ans, nowCnt)
            else:
                nowCnt = 1
        return ans

同步发文于CSDN和我的个人博客,原创不易,转载经作者同意后请附上原文链接哦~

Tisfy:https://letmefly.blog.csdn.net/article/details/142366701

相关推荐
Erik_LinX1 分钟前
算法日记25:01背包(DFS->记忆化搜索->倒叙DP->顺序DP->空间优化)
算法·深度优先
Alidme8 分钟前
cs106x-lecture14(Autumn 2017)-SPL实现
c++·学习·算法·codestepbystep·cs106x
小王努力学编程9 分钟前
【算法与数据结构】单调队列
数据结构·c++·学习·算法·leetcode
最遥远的瞬间11 分钟前
15-贪心算法
算法·贪心算法
维齐洛波奇特利(male)1 小时前
(动态规划 完全背包 **)leetcode279完全平方数
算法·动态规划
项目申报小狂人2 小时前
改进收敛因子和比例权重的灰狼优化算法【期刊论文完美复现】(Matlab代码实现)
开发语言·算法·matlab
让我们一起加油好吗2 小时前
【排序算法】六大比较类排序算法——插入排序、选择排序、冒泡排序、希尔排序、快速排序、归并排序【详解】
c语言·算法·排序算法
夏末秋也凉2 小时前
力扣-贪心-53 最大子数组和
数据结构·算法·leetcode
liruiqiang053 小时前
机器学习 - 投票感知器
人工智能·算法·机器学习
学编程的小程8 小时前
LeetCode216
算法·深度优先