Skip to content

Commit 36712ba

Browse files
authored
Added question description and comments to the code.
Given a string s, find the length of the longest substring without repeating characters. Example 1: Input: s = "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3. Example 2: Input: s = "bbbbb" Output: 1 Explanation: The answer is "b", with the length of 1. Example 3: Input: s = "pwwkew" Output: 3 Explanation: The answer is "wke", with the length of 3. Notice that the answer must be a substring, "pwke" is a subsequence and not a substring. Example 4: Input: s = "" Output: 0 Constraints: 0 <= s.length <= 5 * 104 s consists of English letters, digits, symbols and spaces.
1 parent e70906a commit 36712ba

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
int lengthOfLongestSubstring(string s) {
2+
if(s.length()<=1)
3+
return s.length();
4+
vector<int> freq(128,0);
5+
int si=0,ei=0,n=s.length(),maxlen=INT_MIN,count=0;
6+
while(ei<n){
7+
if(freq[s[ei++]]++ > 0)
8+
count++;
9+
10+
while(count>0){ //if freq of char at ei in the chosen substring is greater than 2
11+
if(freq[s[si++]]-- >1) //iterate till the freq becomes 1
12+
count--;
13+
}
14+
15+
if(ei-si>maxlen) //each time compare length of obtained substr with unique char to the maximum length
16+
maxlen=ei-si;
17+
}
18+
return maxlen;
19+
}

0 commit comments

Comments
 (0)