当前位置: 首页> 健康> 养生 > 苏州苏网建设工程有限公司_拓普建站推广_做品牌推广应该怎么做_seo快速排名站外流量推广

苏州苏网建设工程有限公司_拓普建站推广_做品牌推广应该怎么做_seo快速排名站外流量推广

时间:2025/7/11 0:36:52来源:https://blog.csdn.net/Tisfy/article/details/142366701 浏览次数:0次
苏州苏网建设工程有限公司_拓普建站推广_做品牌推广应该怎么做_seo快速排名站外流量推广

【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 <= 105
  • 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++
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
package mainfunc longestContinuousSubstring(s string) int {ans, nowCnt := 1, 1for 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
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
class Solution:def longestContinuousSubstring(self, s: str) -> int:nowCnt, ans = 1, 1for i in range(1, len(s)):if ord(s[i]) == ord(s[i - 1]) + 1:nowCnt += 1ans = max(ans, nowCnt)else:nowCnt = 1return ans

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

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

关键字:苏州苏网建设工程有限公司_拓普建站推广_做品牌推广应该怎么做_seo快速排名站外流量推广

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: