Skip to main content

Posts

Showing posts with the label Longest Distinct Characters in String

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++: #include<iostream> #include<bits/stdc++.h> using namespace std; int longestDistinctCharacters(string s) {     map<char,int> m;     int c=0,l=0;     for(int i=0;i<s.length();i++)     {         if(m.find(s[i])==m.end())         {             m[s[i]]=i;             c++;         }         else         {             if(l<c)             {                 l=c;             }             i=m[s[i]];             c=0;             m.clear();         }     }     if(l<c)     {         l=c;     }     return l; } int main()  { int t; cin>>t; while(t--) {     string s;     cin>>s;     cin.ignore();     cout<<longestDistinctCharacters(s)<<endl; } return 0; } Here is the Video: