Menu Close

Leetcode 2414: Length of the Longest Alphabetical Continuous Substring Solution

Here, we will see how to solve Length of the Longest Alphabetical Continuous Substring Solution of leet code 2414 problem with code.

You are given an alphabetical continuous string. 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".

Example:

1)
str = "abacaba"
Output: 2
Explanation: There are 4 distinct continuous substrings: "a", "b", "c" and "ab".
"ab" is the longest continuous substring.

2)
str = "abcde"
Output: 5
Explanation: "abcde" is the longest continuous substring.

Length of the Longest Alphabetical Continuous Substring Solution code in C++

Code 1:

#include <iostream>

using namespace std;

int longestContinuousSubstring(string s) {
    int max = 1, count = 1;
        
    for(int i = 0; i < s.length() - 1; i++) {
        
        // Compare with ASCII value of character in string
        if((s[i] + 1) == s[i+1]) {
            count++;
        } else {
            if(max < count) {
                max = count;
            }
            count = 1;
        }
    }
    max = max < count ? count : max;
        
    return max;
}

int main()
{
    cout<<longestContinuousSubstring("abacaba");

    return 0;
}

Output:

2

To check more leetcode problem’s solution. Pls click given below link:

https://www.techieindoor.com/category/leetcode/

Posted in C++, Easy, Leetcode

Leave a Reply

Your email address will not be published. Required fields are marked *