Program to find length of substring with consecutive common characters in Python
-
07-10-2020 - |
Вопрос
Program to find length of substring with consecutive common characters in Python
Suppose we have a string s, we have to find the length of the longest substring with same characters.
So, if the input is like "abbbaccabbbba", then the output will be 4, as there are four consecutive b's.
To solve this, we will follow these steps −
- if size of s is 0, then
- return 0
- s := s concatenate blank space
- ct:= 1, tem:= 1
- for i in range 0 to size of s -2, do
- if s[i] is same as s[i+1], then
- tem := tem + 1
- otherwise,
- ct:= maximum of tem and ct
- tem:= 1
- if s[i] is same as s[i+1], then
- return ct
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, s): if len(s)==0: return 0 s+=' ' ct=1 tem=1 for i in range(len(s)-1): if s[i]==s[i+1]: tem+=1 else: ct=max(tem,ct) tem=1 return ct ob = Solution() print(ob.solve("abbbaccabbbba"))
Input
"abbbaccabbbba"
Output
4
Advertisements
Не связан с Tutorialspoint