Solitary String

QUESTION

In order to celebrate Women’s day, Stella started playing with string S. She needs to know the maximum number of characters between any 2 same characters in the string.\n\nAs she is busy in playing, help her for the same.\n\nIf there are no 2 same characters in the string, print 1.\n\nNote: String is composed of lowercase letters of the Latin alphabet.\n\nInput:\nFirst line contains one integer T, denoting the number of test cases. \nEach of the next T line contains one string S.\n\nOutput:\nFor each test case, output the maximum number of characters between any 2 same characters in the string. If there are no 2 same characters in the string, print 1. \nPrint answer for each test case in a new line.\n\nConstraints:\n\n1T10 \n1|S|10^5, where \n|S| determines the length of the string.\nString is composed of lowercase alphabets ranging from a to z.

ANSWER

#include <iostream>
using namespace std;
void solve()
{
  string s;
  cin>>s;
  int p[50],res=-1;
  for(char c='a';c<='z';c++)
    p[c-'a']=-1;
  for(int i=0;i<s.length();i++)
    if(p[s[i]-'a']==-1)
      p[s[i]-'a']=i;
  else
    res=max(res,i-p[s[i]-'a']-1);
  cout<<res<<endl;
}
int main()
{
  int t;
  cin>>t;
  while(t--)
    solve();
	return 0;
}
Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.

Powered By
100% Free SEO Tools - Tool Kits PRO