comments | difficulty | edit_url | rating | source | tags | |
---|---|---|---|---|---|---|
true |
中等 |
1221 |
第 311 场周赛 Q2 |
|
字母序连续字符串 是由字母表中连续字母组成的字符串。换句话说,字符串 "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
由小写英文字母组成
我们用双指针
时间复杂度
class Solution:
def longestContinuousSubstring(self, s: str) -> int:
ans = 0
i, j = 0, 1
while j < len(s):
ans = max(ans, j - i)
if ord(s[j]) - ord(s[j - 1]) != 1:
i = j
j += 1
ans = max(ans, j - i)
return ans
class Solution {
public int longestContinuousSubstring(String s) {
int ans = 0;
int i = 0, j = 1;
for (; j < s.length(); ++j) {
ans = Math.max(ans, j - i);
if (s.charAt(j) - s.charAt(j - 1) != 1) {
i = j;
}
}
ans = Math.max(ans, j - i);
return ans;
}
}
class Solution {
public:
int longestContinuousSubstring(string s) {
int ans = 0;
int i = 0, j = 1;
for (; j < s.size(); ++j) {
ans = max(ans, j - i);
if (s[j] - s[j - 1] != 1) {
i = j;
}
}
ans = max(ans, j - i);
return ans;
}
};
func longestContinuousSubstring(s string) int {
ans := 0
i, j := 0, 1
for ; j < len(s); j++ {
ans = max(ans, j-i)
if s[j]-s[j-1] != 1 {
i = j
}
}
ans = max(ans, j-i)
return ans
}
function longestContinuousSubstring(s: string): number {
const n = s.length;
let res = 1;
let i = 0;
for (let j = 1; j < n; j++) {
if (s[j].charCodeAt(0) - s[j - 1].charCodeAt(0) !== 1) {
res = Math.max(res, j - i);
i = j;
}
}
return Math.max(res, n - i);
}
impl Solution {
pub fn longest_continuous_substring(s: String) -> i32 {
let s = s.as_bytes();
let n = s.len();
let mut res = 1;
let mut i = 0;
for j in 1..n {
if s[j] - s[j - 1] != 1 {
res = res.max(j - i);
i = j;
}
}
res.max(n - i) as i32
}
}
#define max(a, b) (((a) > (b)) ? (a) : (b))
int longestContinuousSubstring(char* s) {
int n = strlen(s);
int i = 0;
int res = 1;
for (int j = 1; j < n; j++) {
if (s[j] - s[j - 1] != 1) {
res = max(res, j - i);
i = j;
}
}
return max(res, n - i);
}