Skip to main content

Longest Distinct Characters in String

Task: Given a string S, Find the longest sub string with all distinct characters.

Example:
Input:
1
abca
Output:
abc

Here is the Code:
Program in C++:

  1. #include<iostream>
  2. #include<bits/stdc++.h>
  3. using namespace std;
  4. int longestDistinctCharacters(string s)
  5. {
  6.     map<char,int> m;
  7.     int c=0,l=0;
  8.     for(int i=0;i<s.length();i++)
  9.     {
  10.         if(m.find(s[i])==m.end())
  11.         {
  12.             m[s[i]]=i;
  13.             c++;
  14.         }
  15.         else
  16.         {
  17.             if(l<c)
  18.             {
  19.                 l=c;
  20.             }
  21.             i=m[s[i]];
  22.             c=0;
  23.             m.clear();
  24.         }
  25.     }
  26.     if(l<c)
  27.     {
  28.         l=c;
  29.     }
  30.     return l;
  31. }
  32. int main()
  33.  {
  34. int t;
  35. cin>>t;
  36. while(t--)
  37. {
  38.     string s;
  39.     cin>>s;
  40.     cin.ignore();
  41.     cout<<longestDistinctCharacters(s)<<endl;
  42. }
  43. return 0;
  44. }


Here is the Video: