forked from daiwb/Algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlengthOfLongestSubstring.cpp
More file actions
41 lines (40 loc) · 1.03 KB
/
lengthOfLongestSubstring.cpp
File metadata and controls
41 lines (40 loc) · 1.03 KB
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
#include <iostream>
#include <vector>
#include <map>
#include <iterator>
using namespace std;
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int len = s.length();
if (len == 0) return 0;
vector<int> prev(len);
map<char, int> mp;
map<char, int>::iterator itr;
for (int i = 0; i < len; ++i) {
itr = mp.find(s[i]);
if (itr == mp.end()) prev[i] = -1;
else prev[i] = mp[s[i]];
mp[s[i]] = i;
}
int ret = 1, add = 0;
for (int i = len - 1; i >= 0; --i) {
int p = prev[i];
if (p == -1) {
++add;
ret = max(ret, add);
continue;
}
if (i - p + add <= ret) {
add = 0;
continue;
}
for (int j = i - 1; j > p; --j) {
if (prev[j] > p) p = prev[j];
}
ret = max(ret, i - p + add);
add = 0;
}
return ret;
}
};