xrisk
xrisk

Reputation: 3898

Find the length of the longest trailing substring

I need to extract the length of the longest substring that ends at the end of the given string and also contains exactly the same character.

For example, given "aaabbbb" the required substring would be "bbbb" with length = 4

While I can think of many ways to do this using while/for loop, I was wondering if there is a more elegant way to do this. Is there any module for this purpose? I do not want to use a for loop to find this substring. Is it possible?

Upvotes: 0

Views: 175

Answers (2)

Kenneth E. Bellock
Kenneth E. Bellock

Reputation: 1056

>> s = "aaabbbb"
>> len(s) - len(s.rstrip(s[-1]))
4

From the docstring of rstrip

S.rstrip([chars]) -> string or unicode

Return a copy of the string S with trailing whitespace removed. If chars is given and not None, remove characters in chars instead. If chars is unicode, S will be converted to unicode before stripping

So this solution takes the length of the original string, and subtracts from it the length of a string where all the identical last characters are stripped off.

Upvotes: 6

Bhargav Rao
Bhargav Rao

Reputation: 52081

You can try using the re module along with re.escape

>>> s = "aaabbbb"
>>> import re
>>> pat = re.escape(s[-1]) + '*$'
>>> pat
'b*$'
>>> re.search(pat,s).group()
'bbbb'

Other cases

>>> s = 'bbbabbbbb'
>>> re.search(pat,s).group()
'bbbbb'
>>> s = 'abcd'
>>> re.search(pat,s).group()
'd'

You can then use the len to find the length.

Upvotes: 1

Related Questions