Length of the longest substring with consecutive characters

28 Jan, 2022
Given string str of lowercase alphabets, the task is to find the length of the longest substring of characters in alphabetical order i.e. string “dfabck” will return 3. Note that the alphabetical order here is considered circular i.e. a, b, c, d, e, ..., x, y, z, a, b, c, .... 
Examples: 
Input: str = “abcabcdefabc” Output: 6 All valid sub-strings are “abc”, “abcdef” and “abc” And, the length of the longest of these is 6
Input: str = “zabcd” Output: 5 
Approach:  
Initialize i = 0 and len = 0 and starting from i find the ending index of the longest valid sub-string and store it, in end.Now, update len = max(end – i + 1, len) and i = end + 1 (to get the next valid sub-string starting from the index end + 1) and repeat step 1 until i < len(str).Print the value of len in the end.
Initialize i = 0 and len = 0 and starting from i find the ending index of the longest valid sub-string and store it, in end.
Now, update len = max(end – i + 1, len) and i = end + 1 (to get the next valid sub-string starting from the index end + 1) and repeat step 1 until i < len(str).
Print the value of len in the end.
Below is the implementation of the above approach: 
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of the approach#include<bits/stdc++.h>using namespace std;     // Function to return the ending index for the    // largest valid sub-string starting from index i    int getEndingIndex(string str, int n, int i)    {        i++;        while (i < n)        {            char curr = str[i];            char prev = str[i-1];             // If the current character appears after            // the previous character according to            // the given circular alphabetical order            if ((curr == 'a' && prev == 'z') ||                (curr - prev == 1))                i++;            else                break;        }         return i - 1;    }     // Function to return the length of the longest    // sub-string of consecutive characters from str    int largestSubStr(string str, int n)    {        int len = 0;         int i = 0;        while (i < n)        {             // Valid sub-string exists from index            // i to end            int end = getEndingIndex(str, n, i);             // Update the length            len = max(end - i + 1, len);            i = end + 1;        }         return len;    }     // Driver code    int main()    {        string str = "abcabcdefabc";        int n = str.length();        cout << (largestSubStr(str, n));    } // This code is contributed by// Surendra_Gangwar
// Java implementation of the approachclass GFG {     // Function to return the ending index for the    // largest valid sub-string starting from index i    static int getEndingIndex(String str, int n, int i)    {        i++;        while (i < n) {            char curr = str.charAt(i);            char prev = str.charAt(i - 1);             // If the current character appears after            // the previous character  according to            // the given circular alphabetical order            if ((curr == 'a' && prev == 'z') ||                (curr - prev == 1))                i++;            else                break;        }         return i - 1;    }     // Function to return the length of the longest    // sub-string of consecutive characters from str    static int largestSubStr(String str, int n)    {        int len = 0;         int i = 0;        while (i < n) {             // Valid sub-string exists from index            // i to end            int end = getEndingIndex(str, n, i);             // Update the length            len = Math.max(end - i + 1, len);            i = end + 1;        }         return len;    }     // Driver code    public static void main(String args[])    {        String str = "abcabcdefabc";        int n = str.length();         System.out.print(largestSubStr(str, n));    }}
# Python3 implementation of the approach # Function to return the ending index for the# largest valid sub-string starting from index idef getEndingIndex(str1, n, i):     i += 1    while (i < n):             curr = str1[i]        prev = str1[i - 1]         # If the current character appears after        # the previous character according to        # the given circular alphabetical order        if ((curr == 'a' and prev == 'z') or            (ord(curr) - ord(prev) == 1)):            i += 1        else:            break         return i - 1 # Function to return the length of the# longest sub-string of consecutive# characters from str1def largestSubstr1(str1, n):     Len = 0     i = 0    while (i < n):             # Valid sub-string exists from        # index i to end        end = getEndingIndex(str1, n, i)         # Update the Length        Len = max(end - i + 1, Len)        i = end + 1         return Len # Driver codestr1 = "abcabcdefabc"n = len(str1)print(largestSubstr1(str1, n)) # This code is contributed by# Mohit Kumar 29
// C# implementation of the approachusing System; class GFG{     // Function to return the ending index for the    // largest valid sub-string starting from index i    static int getEndingIndex(string str, int n, int i)    {        i++;        while (i < n)        {            char curr = str[i];            char prev = str[i - 1];             // If the current character appears after            // the previous character according to            // the given circular alphabetical order            if ((curr == 'a' && prev == 'z') ||                (curr - prev == 1))                i++;            else                break;        }        return i - 1;    }     // Function to return the length of the longest    // sub-string of consecutive characters from str    static int largestSubStr(string str, int n)    {        int len = 0;         int i = 0;        while (i < n)        {             // Valid sub-string exists from index            // i to end            int end = getEndingIndex(str, n, i);             // Update the length            len = Math.Max(end - i + 1, len);            i = end + 1;        }        return len;    }     // Driver code    public static void Main()    {        string str = "abcabcdefabc";        int n = str.Length;        Console.Write(largestSubStr(str, n));    }} // This code is contributed// by Akanksha Rai
<?php// PHP implementation of the approach // Function to return the ending index// for the largest valid sub-string/// starting from index ifunction getEndingIndex($str, $n, $i){    $i++;    while ($i < $n)    {        $curr = $str[$i];        $prev = $str[$i - 1];         // If the current character appears after        // the previous character according to        // the given circular alphabetical order        if (($curr == 'a' && $prev == 'z') ||            (ord($curr) - ord($prev) == 1))            $i++;        else            break;    }     return $i - 1;} // Function to return the length of the longest// sub-string of consecutive characters from strfunction largestSubStr($str, $n){    $len = 0;     $i = 0;    while ($i < $n)    {         // Valid sub-string exists from index        // i to end        $end = getEndingIndex($str, $n, $i);         // Update the length        $len = max($end - $i + 1, $len);        $i = $end + 1;    }     return $len;} // Driver code$str = "abcabcdefabc";$n = strlen($str);echo largestSubStr($str, $n); // This code is contributed by Ryuga?>
<script>// Javascript implementation of the approach // Function to return the ending index for the// largest valid sub-string starting from index ifunction getEndingIndex(str,n,i){        i++;          while (i < n) {            let curr = str[i];            let prev = str[i - 1];               // If the current character appears after            // the previous character  according to            // the given circular alphabetical order            if ((curr == 'a' && prev == 'z') ||                (curr.charCodeAt(0) - prev.charCodeAt(0) == 1))                i++;            else                break;        }           return i - 1;} // Function to return the length of the longest// sub-string of consecutive characters from strfunction largestSubStr(str,n){        let len = 0;           let i = 0;        while (i < n) {               // Valid sub-string exists from index            // i to end            let end = getEndingIndex(str, n, i);               // Update the length            len = Math.max(end - i + 1, len);            i = end + 1;        }           return len;} // Driver codelet str = "abcabcdefabc";let n = str.length; document.write(largestSubStr(str, n));  // This code is contributed by patel2127</script>
6
 
Time Complexity: O(n) where n is the length of the input string. Note that we increase the index by the end. 
SURENDRA_GANGWAR
mohit kumar 29
Akanksha_Rai
ankthon
patel2127
simmytarika5
array-traversal-question
Java Programs
Pattern Searching
Pattern Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Iterate Over the Characters of a String in Java
How to Convert Char to String in Java?
How to Get Elements By Index from HashSet in Java?
Java Program to Write into a File
How to Write Data into Excel Sheet using Java?
KMP Algorithm for Pattern Searching
Rabin-Karp Algorithm for Pattern Searching
Check if a string is substring of another
Check if an URL is valid or not using Regular Expression
Boyer Moore Algorithm for Pattern Searching