![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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