Open In App

Python | Find longest consecutive letter and digit substring

Improve
Improve
Like Article
Like
Save
Share
Report

Given a String (may contain both letters and digits), write a Python program to find the longest consecutive letter and digit substring. Examples:

Input : geeks123available
Output : ('available', 123)

Input : 98apple658pine
Output : ('apple', 658)

  Approach #1 : Brute force This is the Naive or brute force approach to find the longest consecutive letter and digit substring. We take two string type variable longest_letter and longest_digit. We start a loop and check for consecutive substrings of letter and digit. In each iteration, we check if the current letter substring is longer than the longest letter or digit substring respectively. If yes, we assign the current substring of letter and digit to the longest letter and digit substring respectively. Otherwise, do nothing. 

Python3




# Python3 program to find the longest
# consecutive substring of a certain type
import re
 
def longestSubstring(s):
     
    longest_letterSeq = ''
    longest_digitSeq = ''
    i = 0
    while(i<len(s)):
         
        curr_letterSeq = ''
        curr_digitSeq = ''
         
        # For letter substring
        while(i<len(s) and s[i].isalpha()):
            curr_letterSeq += s[i]
            i+= 1
 
        # For digit substring
        while(i<len(s) and s[i].isdigit()):
            curr_digitSeq += s[i]
            i+= 1
 
        # Case handling if the character
        # is neither letter nor digit   
        if(i< len(s) and not(s[i].isdigit())
                     and not(s[i].isalpha())) :
            i+= 1
         
        if(len(curr_letterSeq) > len(longest_letterSeq) ):
            longest_letterSeq = curr_letterSeq
             
        if(len(curr_digitSeq) > len(longest_digitSeq) ):
            longest_digitSeq = curr_digitSeq
         
    return longest_letterSeq, longest_digitSeq
 
# Driver Code
str = '3Geeksfor123geeks3'
print(longestSubstring(str))


Output:

('Geeksfor', '123')

  Approach #2 : Using Python regex Python Regex is another method to solve the given problem. Find the substring sequence of digits and letters using Python regex and then find the longest substring length respectively. 

Python3




# Python3 program to find the longest
# consecutive substring of a certain type
import re
 
def longestSubstring(str):
    letter = max(re.findall(r'\D+', str), key = len)
    digit = max(re.findall(r'\d+', str), key = len)
     
    return letter, digit
 
# Driver Code
str = 'geeks123geeksforgeeks1'
print(longestSubstring(str))


Output:

('geeksforgeeks', '123')

Time Complexity: O(n), where n is the length of string str.

Space Complexity: O(1).

Method#3:using Sliding window approach

Approach

The approach first initializes empty strings for longest_alpha, longest_num, alpha and num. Then, it iterates through each character in the given string s. If the character is a letter, it appends it to alpha. If the length of alpha is greater than the length of longest_alpha, longest_alpha is updated to alpha and num is reset to an empty string. If the character is a digit, it appends it to num. If the length of num is greater than the length of longest_num, longest_num is updated to num and alpha is reset to an empty string. If the character is not a letter or a digit, both alpha and num are reset to empty strings. Finally, the function returns a tuple of longest_alpha and longest_num if both of them are not empty, otherwise it returns None.

Algorithm

1. Initialize empty strings longest_alpha, longest_num, alpha and num.
2. For each character c in the string s:
a. If c is a letter, append it to alpha.
i. If the length of alpha is greater than the length of longest_alpha, update longest_alpha to alpha and reset num to an empty string.
b. If c is a digit, append it to num.
i. If the length of num is greater than the length of longest_num, update longest_num to num and reset alpha to an empty string.
c. If c is not a letter or a digit, reset both alpha and num to empty strings.
3. Return a tuple of longest_alpha and longest_num if both of them are not empty, otherwise return None.

Python3




def longest_consecutive_substring(s):
    longest_alpha = ""
    longest_num = ""
    alpha = ""
    num = ""
    for c in s:
        if c.isalpha():
            alpha += c
            if len(alpha) > len(longest_alpha):
                longest_alpha = alpha
                num = ""
        elif c.isdigit():
            num += c
            if len(num) > len(longest_num):
                longest_num = num
                alpha = ""
        else:
            alpha = ""
            num = ""
    return (longest_alpha, longest_num) if longest_alpha and longest_num else None
  
s='geeks123available'
print(longest_consecutive_substring(s))


Output

('available', '123')

Time Complexity: O(n), where n is the length of the input string s.

Space Complexity: O(1), as the amount of extra space used is constant, regardless of the length of s.

Method #4: Using the lambda function 

In this method, the lambda function longestSubstring uses the re.findall() function to find all the letter and digit substrings in the input string s. The max() function with the key=len argument is then used to find the longest substring in each list of substrings returned by re.findall(). Finally, the function returns a tuple of the longest letter and digit substrings found in the input string.

Python3




import re
 
longestSubstring = lambda s: (max(re.findall('[a-zA-Z]+', s), key=len), max(re.findall('\d+', s), key=len))
 
# Driver Code
s = '3Geeksfor123geeks3'
print(longestSubstring(s))


Output

('Geeksfor', '123')

Time Complexity: O(n), where n is the length of the input string s. 

Space Complexity: O(1), as only a few variables are being used to store the longest letter and digit substrings. 



Last Updated : 02 May, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads