class Solution {
public:
int longestContinuousSubstring(string s) {
}
};
2414. 最长的字母序连续子字符串的长度
字母序连续字符串 是由字母表中连续字母组成的字符串。换句话说,字符串 "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
由小写英文字母组成原站题解
php 解法, 执行用时: 105 ms, 内存消耗: 20.5 MB, 提交时间: 2024-09-19 09:43:08
class Solution { /** * @param String $s * @return Integer */ function longestContinuousSubstring($s) { $start = 0; $ans = 0; for ( $i=1; $i < strlen($s); $i++ ) { if ( ord($s[$i]) != ord($s[$i-1]) + 1 ) { $ans = max($ans, $i - $start); $start = $i; } } return max($ans, strlen($s) - $start); } }
rust 解法, 执行用时: 0 ms, 内存消耗: 2.2 MB, 提交时间: 2024-09-19 09:38:35
impl Solution { pub fn longest_continuous_substring(s: String) -> i32 { let mut ans = 1; let mut cnt = 1; let s = s.as_bytes(); for i in 1..s.len() { if s[i - 1] + 1 == s[i] { cnt += 1; ans = ans.max(cnt); } else { cnt = 1; } } ans } }
javascript 解法, 执行用时: 70 ms, 内存消耗: 54.7 MB, 提交时间: 2024-09-19 09:38:20
/** * @param {string} s * @return {number} */ var longestContinuousSubstring = function(s) { let ans = 1, cnt = 1; for (let i = 1; i < s.length; i++) { if (s.charCodeAt(i - 1) + 1 === s.charCodeAt(i)) { ans = Math.max(ans, ++cnt); } else { cnt = 1; } } return ans; };
cpp 解法, 执行用时: 40 ms, 内存消耗: 16.5 MB, 提交时间: 2024-09-19 09:38:07
class Solution { public: int longestContinuousSubstring(string s) { int ans = 1, cnt = 1; for (int i = 1; i < s.length(); i++) { if (s[i - 1] + 1 == s[i]) { ans = max(ans, ++cnt); } else { cnt = 1; } } return ans; } };
java 解法, 执行用时: 6 ms, 内存消耗: 44.3 MB, 提交时间: 2024-09-19 09:37:52
class Solution { public int longestContinuousSubstring(String S) { char[] s = S.toCharArray(); int ans = 1; int cnt = 1; for (int i = 1; i < s.length; i++) { if (s[i - 1] + 1 == s[i]) { ans = Math.max(ans, ++cnt); } else { cnt = 1; } } return ans; } }
golang 解法, 执行用时: 8 ms, 内存消耗: 6.3 MB, 提交时间: 2022-11-22 16:07:15
func longestContinuousSubstring(s string) (ans int) { start := 0 for i := 1; i < len(s); i++ { if s[i] != s[i-1]+1 { ans = max(ans, i-start) start = i // 新起点 } } return max(ans, len(s)-start) } func max(a, b int) int { if b > a { return b }; return a }
python3 解法, 执行用时: 508 ms, 内存消耗: 15.5 MB, 提交时间: 2022-11-22 16:06:57
class Solution: def longestContinuousSubstring(self, s: str) -> int: ans = start = 0 for i in range(1, len(s)): if ord(s[i]) != ord(s[i - 1]) + 1: ans = max(ans, i - start) start = i # 新起点 return max(ans, len(s) - start)