-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlongest.cpp
45 lines (40 loc) · 1.09 KB
/
longest.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
#include <iostream>
#include <map>
#include <iterator>
using namespace std;
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int start = 0;
int end = 0;
int len = s.length();
map <char, int> amap;
int maxLen = 0;
int currlen = 0;
while (end < len){
char curr = s.at(end);
// found in prev checked
if (amap.count(curr)){
int prevStart = start;
start = amap[curr] + 1;
for (int i = prevStart; i < start; ++i) {
amap.erase(s.at(i));
}
}else{
amap.insert({curr, end});
end++;
currlen = end - start;
if ((currlen) > maxLen){
maxLen = currlen;
}
}
}
return maxLen;
}
};
int main(int argc, char **argv){
Solution s;
string str = "aaaaaaabcd";
int result = s.lengthOfLongestSubstring(str);
printf("Longest substring of \"%s\" is: %d\n", str.c_str(), result);
}