comments | difficulty | edit_url | rating | source | tags | |
---|---|---|---|---|---|---|
true |
Medium |
1221 |
Weekly Contest 311 Q2 |
|
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"
.
- For example,
"abc"
is an alphabetical continuous string, while"acb"
and"za"
are not.
Given a string s
consisting of lowercase letters only, return the length of the longest alphabetical continuous substring.
Example 1:
Input: s = "abacaba" Output: 2 Explanation: There are 4 distinct continuous substrings: "a", "b", "c" and "ab". "ab" is the longest continuous substring.
Example 2:
Input: s = "abcde" Output: 5 Explanation: "abcde" is the longest continuous substring.
Constraints:
1 <= s.length <= 105
s
consists of only English lowercase letters.
We can traverse the string
Next, we start traversing the string
Finally, we return
The time complexity is
class Solution:
def longestContinuousSubstring(self, s: str) -> int:
ans = cnt = 1
for x, y in pairwise(map(ord, s)):
if y - x == 1:
cnt += 1
ans = max(ans, cnt)
else:
cnt = 1
return ans
class Solution {
public int longestContinuousSubstring(String s) {
int ans = 1, cnt = 1;
for (int i = 1; i < s.length(); ++i) {
if (s.charAt(i) - s.charAt(i - 1) == 1) {
ans = Math.max(ans, ++cnt);
} else {
cnt = 1;
}
}
return ans;
}
}
class Solution {
public:
int longestContinuousSubstring(string s) {
int ans = 1, cnt = 1;
for (int i = 1; i < s.size(); ++i) {
if (s[i] - s[i - 1] == 1) {
ans = max(ans, ++cnt);
} else {
cnt = 1;
}
}
return ans;
}
};
func longestContinuousSubstring(s string) int {
ans, cnt := 1, 1
for i := range s[1:] {
if s[i+1]-s[i] == 1 {
cnt++
ans = max(ans, cnt)
} else {
cnt = 1
}
}
return ans
}
function longestContinuousSubstring(s: string): number {
let [ans, cnt] = [1, 1];
for (let i = 1; i < s.length; ++i) {
if (s.charCodeAt(i) - s.charCodeAt(i - 1) === 1) {
ans = Math.max(ans, ++cnt);
} else {
cnt = 1;
}
}
return ans;
}
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] - s[i - 1] == 1 {
cnt += 1;
ans = ans.max(cnt);
} else {
cnt = 1;
}
}
ans
}
}
#define max(a, b) (((a) > (b)) ? (a) : (b))
int longestContinuousSubstring(char* s) {
int n = strlen(s);
int ans = 1, cnt = 1;
for (int i = 1; i < n; ++i) {
if (s[i] - s[i - 1] == 1) {
++cnt;
ans = max(ans, cnt);
} else {
cnt = 1;
}
}
return ans;
}