-
Notifications
You must be signed in to change notification settings - Fork 0
/
LengthOfLongestSubString.cpp
45 lines (38 loc) · 1.27 KB
/
LengthOfLongestSubString.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/* https://leetcode.com/problems/longest-substring-without-repeating-characters/description/#
#hash-table #string #slicing-window #two-pointer
*/
#include<iostream>
#include<map>
using namespace std;
// O(n)
int lengthOfLongestSubstring(string s) {
int maxLength = 0; // length of longest subString
int firstIndex = 0; // first index of subString
int lengthSub = 0; // length of subString
if(s.empty())
return 0;
map<char, int> hashMap;
for(int i = 0; i < s.length(); ++i) {
map<char, int>::iterator it= hashMap.find(s[i]);
if (it == hashMap.end()){
++lengthSub;
hashMap.insert(pair<char,int>(s[i],i));
}else {
if (it->second < firstIndex) {
++lengthSub;
} else {
maxLength = lengthSub > maxLength ? lengthSub : maxLength;
firstIndex = it->second + 1;
lengthSub = i - firstIndex + 1;
}
it->second = i;
}
}
return lengthSub > maxLength ? lengthSub : maxLength;
}
//test
int main() {
string s = "dvdfagd";
cout << lengthOfLongestSubstring(s) << endl;
return 0;
}