Largest substring with same Characters
Last Updated :
25 May, 2022
Given a string s of size N. The task is to find the largest substring which consists of the same characters
Examples:
Input : s = “abcdddddeff”
Output : 5
Substring is “ddddd”
Input : s = aabceebeee
Output : 3
Approach :
Traverse through the string from left to right. Take two variables ans and temp. If the current element is the same as the previous element then increment temp. If the current element is not equal to the previous element then make temp as 1 and update ans.
Below is the implementation of the above approach :
C++
#include <bits/stdc++.h>
using namespace std;
int Substring(string s)
{
int ans = 1, temp = 1;
for ( int i = 1; i < s.size(); i++) {
if (s[i] == s[i - 1]) {
++temp;
}
else {
ans = max(ans, temp);
temp = 1;
}
}
ans = max(ans, temp);
return ans;
}
int main()
{
string s = "abcdddddeff" ;
cout << Substring(s);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static int Substring(String s)
{
int ans = 1 , temp = 1 ;
for ( int i = 1 ; i < s.length(); i++)
{
if (s.charAt(i) == s.charAt(i - 1 ))
{
++temp;
}
else
{
ans = Math.max(ans, temp);
temp = 1 ;
}
}
ans = Math.max(ans, temp);
return ans;
}
public static void main(String[] args)
{
String s = "abcdddddeff" ;
System.out.println(Substring(s));
}
}
|
Python3
def Substring(s):
ans, temp = 1 , 1
for i in range ( 1 , len (s)):
if (s[i] = = s[i - 1 ]):
temp + = 1
else :
ans = max (ans, temp)
temp = 1
ans = max (ans, temp)
return ans
s = "abcdddddeff"
print (Substring(s))
|
C#
using System;
class GFG
{
static int Substring(String s)
{
int ans = 1, temp = 1;
for ( int i = 1; i < s.Length; i++)
{
if (s[i] == s[i - 1])
{
++temp;
}
else
{
ans = Math.Max(ans, temp);
temp = 1;
}
}
ans = Math.Max(ans, temp);
return ans;
}
public static void Main(String[] args)
{
String s = "abcdddddeff" ;
Console.WriteLine(Substring(s));
}
}
|
PHP
<?php
function Substring( $s )
{
$ans = 1;
$temp = 1;
for ( $i = 1; $i < strlen ( $s ); $i ++)
{
if ( $s [ $i ] == $s [ $i - 1])
{
++ $temp ;
}
else
{
$ans = max( $ans , $temp );
$temp = 1;
}
}
$ans = max( $ans , $temp );
return $ans ;
}
$s = "abcdddddeff" ;
echo Substring( $s );
?>
|
Javascript
<script>
function Substring(s)
{
var ans = 1, temp = 1;
for ( var i = 1; i < s.length; i++) {
if (s[i] == s[i - 1]) {
++temp;
}
else {
ans = Math.max(ans, temp);
temp = 1;
}
}
ans = Math.max(ans, temp);
return ans;
}
var s = "abcdddddeff" ;
document.write( Substring(s));
</script>
|
Output:
5
Time Complexity: O(N)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...