Python program to find maximum uppercase run
Last Updated :
18 Feb, 2023
Giving a String, write a Python program to find the maximum run of uppercase characters.
Examples:
Input : test_str = ‘GeEKSForGEEksISBESt’
Output : 5
Explanation : ISBES is best run of uppercase.
Input : test_str = ‘GeEKSForGEEKSISBESt’
Output : 10
Explanation : GEEKSISBES is best run of uppercase.
Method : Using isupper() + loop
In this, we update the maximum run when non-uppercase is encountered otherwise counter is incremented if the character is uppercase.
Python3
test_str = 'GeEKSForGEEksIsBESt'
print ( "The original string is : " + str (test_str))
cnt = 0
res = 0
for idx in range ( 0 , len (test_str)):
if test_str[idx].isupper():
cnt + = 1
else :
if res < cnt :
res = cnt
cnt = 0
else :
cnt = 0
if test_str[ len (test_str) - 1 ].isupper():
res = cnt
print ( "Maximum Uppercase Run : " + str (res))
|
Output:
The original string is : GeEKSForGEEksISBESt
Maximum Uppercase Run : 5
The time and space complexity for all the methods are the same:
Time Complexity : O(n)
Auxiliary Space : O(n)
Method : Using re
Another approach to solve this problem would be to use the built-in re module in Python to find all the substrings of consecutive uppercase characters in the given string and then find the maximum length among them. Here is the implementation of the same:
Python3
import re
def max_uppercase_run(test_str):
uppercase_runs = re.findall(r '[A-Z]+' , test_str)
return max ( len (run) for run in uppercase_runs) if uppercase_runs else 0
test_str = "GeEKSForGEEksISBESt"
print ( "The maximum uppercase run is:" , max_uppercase_run(test_str))
test_str = "GeEKSForGEEKSISBESt"
print ( "The maximum uppercase run is:" , max_uppercase_run(test_str))
|
Output
The maximum uppercase run is: 5
The maximum uppercase run is: 10
The time complexity of this approach is O(n), where n is the length of the input string test_str. The space complexity is O(n) as we are storing the substrings in the uppercase_runs list.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...