-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlongest_substring.cpp
More file actions
103 lines (97 loc) · 2.46 KB
/
longest_substring.cpp
File metadata and controls
103 lines (97 loc) · 2.46 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
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
/*
* =====================================================================================
*
* Filename: longest_substring.cpp
*
* Description: 3. Longest Substring Without Repeating Characters.
*
* Version: 1.0
* Created: 01/29/2023 12:14:02
* Revision: none
* Compiler: gcc
*
* Author: xianfeng.zhu@gmail.com
* Organization:
*
* =====================================================================================
*/
#include <algorithm>
#include <cstdio>
#include <initializer_list>
#include <string>
#include <unordered_map>
#include <utility>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
using std::initializer_list;
using std::string;
using std::unordered_map;
using std::vector;
class Solution1 {
public:
int lengthOfLongestSubstring(string s) {
int len = 0;
int left = 0;
for (int i = 0; i < s.size(); i++) {
size_t p = s.find(s[i], left);
if (p == string::npos || p >= i) {
len = std::max(len, i - left + 1);
} else {
len = std::max(len, i - left);
left = static_cast<int>(p + 1);
}
}
return len;
}
};
// Hash table
class Solution2 {
public:
int lengthOfLongestSubstring(string s) {
unordered_map<char, int> indices;
int len = 0;
int left = -1;
for (int i = 0; i < s.size(); i++) {
auto it = indices.find(s[i]);
if (it != indices.end() && it->second >= left) {
left = it->second;
it->second = i;
} else {
indices[s[i]] = i;
}
len = std::max(len, i - left);
}
return len;
}
};
// Replace hash table with vector
class Solution3 {
public:
int lengthOfLongestSubstring(string s) {
vector<int> indices(256, -1);
int len = 0;
int start = -1;
for (int i = 0; i < s.size(); i++) {
const int c = s[i];
if (indices[c] > start) {
start = indices[c];
}
indices[s[i]] = i;
len = std::max(len, i - start);
}
return len;
}
};
TEST(Solution, lengthOfLongestSubstring) {
initializer_list<std::pair<string, int>> cases = {
std::make_pair("abba", 2),
std::make_pair("bbbbb", 1),
std::make_pair("pwwkew", 3),
std::make_pair("abcabcbb", 3),
};
for (const auto& c : cases) {
EXPECT_EQ(Solution1().lengthOfLongestSubstring(c.first), c.second);
EXPECT_EQ(Solution2().lengthOfLongestSubstring(c.first), c.second);
EXPECT_EQ(Solution3().lengthOfLongestSubstring(c.first), c.second);
}
}