Header Ads Widget

One String No Trouble | Hackerearth practice problem solution

   Problem:-

A string s is called a good string if and only if two consecutive letters are not the same. For example, abcab and  cda are good while abaa and accba are not.

You are given a string s. Among all the good substrings of s ,print the size of the longest one.

Input format

A single line that contains a string s (1|s|2105).

Output format

Print an integer that denotes the size of the longest good substring of s.

Sample Input
ab
Sample Output
2
Time Limit: 1
Memory Limit: 256
Source Limit:
Explanation

The complete string is good so the answer is 2.

10

Code:-

  Here I am going to give you two solution first one is on the basis of C language and second one is on the basis of c++ language which you can submit in c++14 and c++17 also

Solution 1 ( C language):-

#include<stdio.h>
#include<string.h>
int main()
{
    char a[200001];
    long int i,m=0,max,s[200000];
    scanf ("%s",a);
    for(i=0;a[i]!='\0';i++)
    {
        if (a[i]==a[i+1])
        {
            s[m]+=1;
            m++;
            continue;
        }
        else
        {
            s[m]+=1;
        }
    }
    max=s[0];
    for(i=1;s[i]!='\0';i++)
    {
        if(s[i]>max)
        max=s[i];
    }
    printf ("%lld",max);
    return 0;
}

Solution 2 ( C++ language):-

 This solution is based on the c++ language and you can submit ib c++14 and c++17 also.

#include<iostream>
using namespace std;
int main()
{
string s;
int sum = 1;
cin >> s;
int max = 1;
for(int i = 1; i<s.length(); i++)
{
if(s[i] != s[i-1])
sum++;
else
{
if(sum > max)
max = sum;
sum = 1;
}
}
if(sum > max)
max = sum;
cout << max;
}

Recommended Post:-

         MCQs:-

Post a Comment

0 Comments