-
Notifications
You must be signed in to change notification settings - Fork 0
/
longest_substring_without_repeating_characters.cpp
79 lines (71 loc) · 2.16 KB
/
longest_substring_without_repeating_characters.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// https://oj.leetcode.com/problems/longest-substring-without-repeating-characters/
// Date: Nov 20, 2014
#include <iostream>
#include <string>
#include <unordered_set>
using namespace std;
class Solution {
public:
int lengthOfLongestSubstring(string str)
{
if (str.size() == 0)
{
return 0;
}
unordered_set<char> max_set, cur_set;
int max_begin, cur_begin;
max_begin = 0;
cur_begin = 0;
max_set.insert(str[0]);
cur_set.insert(str[0]);
for (int ch_i = 1; ch_i != str.size(); ++ch_i)
{
unordered_set<char>::iterator it = cur_set.find(str[ch_i]);
if (it == cur_set.end())
{
cur_set.insert(str[ch_i]);
if (max_set.size() < cur_set.size())
{
max_set = cur_set;
max_begin = cur_begin;
}
/*
if (max_set.size() > 12)
{
cout << "ch_i: " << ch_i << endl;
}
*/
}
else
{
// set the cur_set index from the element just after str[ch_i]
while (true)
{
cur_set.erase(str[cur_begin]);
++cur_begin;
if (str[cur_begin-1] == str[ch_i])
{
break;
}
}
/*
if (cur_set.size() == 0)
{
cout << "cur_begin: " << cur_begin << " :: ch_i: " << ch_i << endl;
}
*/
cur_set.insert(str[ch_i]);
}
}
return max_set.size();
}
};
int main(int argc, char* argv[])
{
//string str = "hnwnkuewhsqmgbbuqcljjivswmdkqtbxixmvtrrbljptnsnfwzqfjmafadrrwsofsbcnuvqhffbsaqxwpqcac";
string str = "wlrbbmqbhcdarzowkkyhiddqscdxrjmowfrxsjybldbefsarcbynecdyggxxpklorellnmpapqfwkhopkmco";
Solution sln;
int len_longest_substr = sln.lengthOfLongestSubstring(str);
cout << "len: " << len_longest_substr << endl;
return 0;
}