Problem Statement:
Return he longest length of the substring with consecutive characters.
Example:
Input: Input: sdfdsioweabcdef
Output: 6
Explanation: "abcdef" is the length of continuous alphabetical substring
Solution Explanation:
We will solve the problem with the help of sliding window approach.
We will check if s[i+1]-s[i] is 1, then update the length.
Else reset the length to 1 and string the window.
Time Complexity: O(n)
Space Complexity: O(1)
Code Solution
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int solution(string s)
{
int n = s.size();
int result = 1;
int length = 1;
int left = 0;
for(int right = 0 ; right <n ;)
{
if(s[right+1]-s[right] == 1)
{
length ++;
result = max(result, length);
}
else
{
length = 1;
left++;
}
right++;
}
return result;
}
int main()
{
string str = "sdfdsioweabcdef";
cout << solution(str);
}
Output
6