-
Notifications
You must be signed in to change notification settings - Fork 0
/
longestsubstring.cpp
51 lines (45 loc) · 1.13 KB
/
longestsubstring.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
46
47
48
49
50
51
//
// longestsubstring.cpp
// xcode
//
// Created by Gokul Nadathur on 9/5/16.
// Copyright © 2016 Gokul Nadathur. All rights reserved.
//
#include <iostream>
#include <unordered_map>
#include <utility>
using namespace std;
class Solution {
public:
void updateLongest(pair<int, int>& longest, int start, int end)
{
auto num = end - start + 1;
if (num > longest.second) {
longest.first = start;
longest.second = num;
}
}
int lengthOfLongestSubstring(string s) {
int start = 0, end = 0;
unordered_map<char, int> check;
pair<int, int> longest(0,-1);
for (auto c : s) {
auto it = check.find(c);
if (it != check.end()) {
auto pos = it->second;
if (pos >= start) {
updateLongest(longest, start, end - 1);
start = pos + 1;
}
}
check[c] = end;
end ++;
}
updateLongest(longest, start, end - 1);
return longest.second;
}
};
int main(int argc, char** argv)
{
return 0;
}