Open In App

Python | Longest Run of given Character in String

Last Updated : 23 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with Strings, we can have a problem in which we need to perform the extraction of length of longest consecution of certain letter. This can have application in web development and competitive programming. Lets discuss certain ways in which this task can be performed. 

Method #1 : Using loop This is brute force method in which we can perform this task. In this, we run a loop over the String and keep on memorizing the maximum whenever the run occurs. 

Python3




# Python3 code to demonstrate working of
# Longest Run of Character in String
# Using loop
 
# initializing string
test_str = 'geeksforgeeeks'
 
# printing original string
print("The original string is : " + test_str)
 
# initializing K
K = 'e'
 
# Longest Run of Character in String
# Using loop
res = 0
cnt = 0
for chr in test_str:
    if chr == K:
        cnt += 1
    else:
        res = max(res, cnt)
        cnt = 0
res = max(res, cnt)
 
# printing result
print("Longest Run length of K : " + str(res))


Output

The original string is : geeksforgeeeks
Longest Run length of K : 3

Time Complexity: O(n)

Auxiliary Space: O(1)

  Method #2 : Using max() + re.findall() This is one liner way in which this problem can be solved. In this, we find the maximum of all runs found using findall(). 

Python3




# Python3 code to demonstrate working of
# Longest Run of Character in String
# Using max() + re.findall()
import re
 
# initializing string
test_str = 'geeksforgeeeks'
 
# printing original string
print("The original string is : " + test_str)
 
# initializing K
K = 'e'
 
# Longest Run of Character in String
# Using max() + re.findall()
res = len(max(re.findall(K + '+', test_str), key = len))
 
# printing result
print("Longest Run length of K : " + str(res))


Output

The original string is : geeksforgeeeks
Longest Run length of K : 3

The Time and Space Complexity for all the methods are the same:

Time Complexity: O(n)

Auxiliary Space: O(n)

Method #3 : Using while loop and max(),pop() methods

Python3




# Python3 code to demonstrate working of
# Longest Run of Character in String
# Using loop
 
# initializing string
test_str = 'geeksforgeeeeeks'
 
# printing original string
print("The original string is : " + test_str)
 
# initializing K
K = 'e'
res=[]
i=1
while(K in test_str):
    K="e"*i
    res.append(i)
    i+=1
res.pop()
ma=max(res)
# printing result
print("Longest Run length of K : " + str(ma))


Output

The original string is : geeksforgeeeeeks
Longest Run length of K : 5

Time Complexity: O(n)

Auxiliary Space: O(n)

Method #4 : Using recursive method

Python3




# Python3 code to demonstrate working of
# Longest Run of Character in String
# Using recursive function
 
def longest_run_recursive(string, k, i=0):
    if i == len(string):  #base condition
        return 0
    if string[i] == k:
        return 1 + longest_run_recursive(string, k, i + 1)
    else:
        return 0
 
 
 
# initializing string
test_str = 'geeksforgeeeeeks'
 
# printing original string
print("The original string is : " + test_str)
 
# initializing K
k = 'e'
 
longest_run = max(longest_run_recursive(test_str, k, i) for i in range(len(test_str)))
 
# printing result
print("Longest Run length of K : " + str(longest_run))
#this code contributed by tvsk


Output

The original string is : geeksforgeeeeeks
Longest Run length of K : 5

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #5: Using itertools groupby()

  • Import the itertools module.
  • Initialize the input string test_str and the target character K.
  • Use itertools.groupby() to group the characters in test_str into consecutive runs of the same character.
  • For each run of the character K, append the length of the run to a list called counts.
  • Find the maximum value in counts, which represents the length of the longest run of the character K in test_str.
  • Print the result.

Python3




import itertools
test_str = 'geeksforgeeeks'
K = 'e'
groups = itertools.groupby(test_str)
counts = []
for k, g in groups:
    if k == K:
        counts.append(len(list(g)))
longest_run = max(counts)
print("Longest Run length of K : " + str(longest_run))
 
#This code is contributed by Vinay Pinjala.


Output

Longest Run length of K : 3

Time complexity: O(n), where n is the length of the input string test_str. This is because itertools.groupby() iterates over each character in test_str exactly once, and appending to a list and finding the maximum value in the list take constant time.

Auxiliary Space: O(k), where k is the number of runs of the character K in test_str. This is because the list counts contains one element for each run of K, and each element takes up constant space. Therefore, the space used by the algorithm is proportional to the number of runs of K in the input string, rather than the length of the input string itself.

Method #6: Using Counter from collections module:

Algorithm:

1.Create a Counter object from the input string using collections.Counter() function.
2.Find the count of the given character in the Counter object using the get() method.
3.Return the count as the result.

Python3




from collections import Counter
 
test_str = 'geeksforgeeeeeks'
K = 'e'
# printing original string
print("The original string is : " + test_str)
 
 
count_dict = Counter(test_str)
longest_run = 0
curr_run = 0
for char in test_str:
    if char == K:
        curr_run += 1
        longest_run = max(longest_run, curr_run)
    else:
        curr_run = 0
 
print("Longest Run length of K : " + str(longest_run))
# This code is contributed by Jyothi pinjala


Output

The original string is : geeksforgeeeeeks
Longest Run length of K : 5

Time Complexity: O(n) (where n is the length of the input string)
The time complexity is dominated by the creation of the Counter object, which takes O(n) time.

Space Complexity: O(k) (where k is the number of unique characters in the input string)
The space complexity is dominated by the space required to store the Counter object, which takes O(k) space.

Method #7: Using regex

Import the re module.
Define a regular expression pattern that matches consecutive occurrences of the target character. For instance, the pattern for the character ‘e’ would be r’e+’.
Use the re.findall() method to find all non-overlapping matches of the pattern in the input string.
Compute the length of each match and return the maximum length.

Python3




import re
 
def longest_run_regex(string, k):
    pattern = r'{}+'.format(k)
    matches = re.findall(pattern, string)
    return max(len(match) for match in matches)
 
test_str = 'geeksforgeeeeeks'
k = 'e'
 
longest_run = longest_run_regex(test_str, k)
print("Longest Run length of K : " + str(longest_run))


Output

Longest Run length of K : 5

The time complexity  O(n^2), where n is the length of the string. 
The space complexity O(n^2), where n is the length of the string. 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads