Skip to content

Commit 624af4c

Browse files
authored
Merge pull request #694 from sriharsha200/my-techdoc
Longest Substring Without Repeating Characters
2 parents 815ec44 + bd1814d commit 624af4c

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/* Longest substring without repeating characters
2+
Given a string s, find the length of the longest substring without repeating characters.
3+
Solution is to use sliding window concept */
4+
#include<bits/stdc++.h>
5+
using namespace std;
6+
int lengthOfLongestSubstring(string s) { // Function to implement length Of Longest Substring
7+
int i=0,j=0,f=1,ans=0;
8+
unordered_map<int,int>m;
9+
while(j<s.length()){
10+
auto it=m.find(s[j]);
11+
if(it==m.end()){
12+
m.insert(pair<int,int>(s[j],1)); // insert new characters in the map
13+
j+=1;
14+
}
15+
else{
16+
if(f==1){
17+
m[s[j]]+=1; // As a sliding window increase frequency of the character
18+
}
19+
if(m[s[j]]>1){ // If frequency is grater then 1 move starting point of window
20+
m[s[i]]-=1;
21+
i+=1;
22+
f=0;
23+
}
24+
else{
25+
j+=1; // Move ending point of window
26+
f=1;
27+
}
28+
}
29+
ans=max(ans,j-i);
30+
}
31+
return ans;
32+
}
33+
int main(){
34+
string s;
35+
cin>>s;
36+
cout<<lengthOfLongestSubstring(s);
37+
}

0 commit comments

Comments
 (0)