Python | Longest Run of given Character in String
Last Updated : 23 Apr, 2023
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))
OutputThe 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))
OutputThe 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))
OutputThe 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
OutputThe 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.
OutputLongest 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
OutputThe 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))
OutputLongest 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.
Similar Reads
Get Last N characters of a string - Python We are given a string and our task is to extract the last N characters from it. For example, if we have a string s = "geeks" and n = 2, then the output will be "ks". Let's explore the most efficient methods to achieve this in Python.Using String Slicing String slicing is the fastest and most straigh
2 min read
Python | Extract length of longest string in list Sometimes, while working with a lot of data, we can have a problem in which we need to extract the maximum length of all the strings in list. This kind of problem can have application in many domains. Let's discuss certain ways in which this task can be performed. Method #1 : Using max() + generator
4 min read
Iterate over characters of a string in Python In this article, we will learn how to iterate over the characters of a string in Python. There are several methods to do this, but we will focus on the most efficient one. The simplest way is to use a loop. Letâs explore this approach.Using for loopThe simplest way to iterate over the characters in
2 min read
Python - Longest Substring Length of K Given a String and a character K, find longest substring length of K. Input : test_str = 'abcaaaacbbaa', K = b Output : 2 Explanation : b occurs twice, 2 > 1. Input : test_str = 'abcaacccbbaa', K = c Output : 3 Explanation : Maximum times c occurs is 3. Method #1: Using loop This is brute way to
7 min read
Find Length of String in Python In this article, we will learn how to find length of a string. Using the built-in function len() is the most efficient method. It returns the number of items in a container. Pythona = "geeks" print(len(a)) Output5 Using for loop and 'in' operatorA string can be iterated over, directly in a for loop.
2 min read