My question is - how can I find a length of the longest substring without certain character?
For example, I want to find a length of the longest substring without letter 'a' in the string 'cbdbabdbcbdacbadbcbbcda' and the answer should be '7' - the longest string without 'a' is 'dbcbbcd'.
What are the possible ways to do it?
CodePudding user response:
Split the string by the certain character, in this case "a", count the lengths of the substrings, and get the maximum.
string = 'cbdbabdbcbdacbadbcbbcda'
avoid = 'a'
longest_substring = max((len(substring) for substring in string.split(avoid)))
print(longest_substring)
This outputs 7.
You can obviously split the comprehension up into multiple lines etc. if that makes it easier to understand.
CodePudding user response:
A regex based approach might use re.findall
with the pattern [b-z]
:
inp = "cbdbabdbcbdacbadbcbbcda"
longest = sorted(re.findall(r'[b-z] ', inp), key=len, reverse=True)[0]
print(longest) # dbcbbcd
print(len(longest)) # 7
CodePudding user response:
You can also use a simple for loop to achieve this.
string = 'cbdbabdbcbdacbadbcbbcda'
avoid = 'a'
max_count, curr_count = 0, 0
for char in string:
if char != avoid:
curr_count = 1
else:
if curr_count > max_count:
max_count = curr_count
curr_count = 0 # Reset curr_count
print(max_count)
Output:
7