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 thelongest alphabetical continuous substring.
We want the longest substring where each character is the next letter in the alphabet compared to the previous one. We can scan the string and keep track of the current window of consecutive letters.
classSolution {
public:int longestContinuousSubstring(string s) {
int ans =1, cur =1;
for (int i =1; i < s.size(); ++i) {
if (s[i] == s[i-1] +1) cur++;
else cur =1;
ans = max(ans, cur);
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
funclongestContinuousSubstring(sstring) int {
ans, cur:=1, 1fori:=1; i < len(s); i++ {
ifs[i] ==s[i-1]+1 {
cur++ } else {
cur = 1 }
ifcur > ans { ans = cur }
}
returnans}
1
2
3
4
5
6
7
8
9
10
11
classSolution {
publicintlongestContinuousSubstring(String s) {
int ans = 1, cur = 1;
for (int i = 1; i < s.length(); i++) {
if (s.charAt(i) == s.charAt(i-1) + 1) cur++;
else cur = 1;
ans = Math.max(ans, cur);
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution {
funlongestContinuousSubstring(s: String): Int {
var ans = 1; var cur = 1for (i in1 until s.length) {
if (s[i] == s[i-1]+1) cur++else cur = 1 ans = maxOf(ans, cur)
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
classSolution:
deflongestContinuousSubstring(self, s: str) -> int:
ans = cur =1for i in range(1, len(s)):
if ord(s[i]) == ord(s[i-1]) +1:
cur +=1else:
cur =1 ans = max(ans, cur)
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
impl Solution {
pubfnlongest_continuous_substring(s: String) -> i32 {
let s = s.as_bytes();
letmut ans =1;
letmut cur =1;
for i in1..s.len() {
if s[i] == s[i-1] +1 {
cur +=1;
} else {
cur =1;
}
ans = ans.max(cur);
}
ans
}
}