-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlongestSubstring.cpp
More file actions
81 lines (65 loc) · 2.27 KB
/
longestSubstring.cpp
File metadata and controls
81 lines (65 loc) · 2.27 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
// https://leetcode.com/problems/longest-substring-without-repeating-characters/
//
// Status: Accepted
// Runtime: 24 ms
// Score: 93.12 %
//
#include <iostream>
#include <map>
#include <gtest/gtest.h>
#include "args.h"
#include "macros.h"
using namespace std;
class Solution {
public:
int lengthOfLongestSubstring(string s) {
// Can be any character, not just alphabet
// Allow for all ASCII characters
vector<bool> characters(128, false);
int N = s.length();
int i=0;
int j=0;
int maxCount = 0;
// Use caterpillar method to inch along finding long substrings
// Use a 32-bit int for tracking characters
// Use counter just so I don't have to count elements
while ( (i<N) && (j<N) ) {
char duplicateLetter = 0;
// Increase j until we get a repeat
while (j<N && !characters[s[j]]) {
characters[s[j]] = true;
j++;
}
maxCount = max(j-i, maxCount);
if ( (j<N) && characters[s[j]] ) {
duplicateLetter = s[j];
}
// Increase i until duplicate letter erased
// (could do until i==j but that is guaranteed to happen)
bool duplicateErased = false;
while (i<=j && (i<N) && !duplicateErased) {
characters[s[i]] = false;
if ( s[i] == duplicateLetter ) {
duplicateErased = true;
}
i++;
}
// go ahead and exit a bit early if maxCount
// isn't going to increase
if ( (j == N) && ((j-i) < maxCount)) {
break;
}
}
return maxCount;
}
};
TEST(LongestSubstring, CorrectTest)
{
Solution solution;
ASSERT_EQ(solution.lengthOfLongestSubstring("abcabcbb"), 3);
ASSERT_EQ(solution.lengthOfLongestSubstring(""), 0);
ASSERT_EQ(solution.lengthOfLongestSubstring("z"), 1);
ASSERT_EQ(solution.lengthOfLongestSubstring("thequickredfoxjumpedoverthebrownlazydog"), 13);
ASSERT_EQ(solution.lengthOfLongestSubstring(" "), 1);
ASSERT_EQ(solution.lengthOfLongestSubstring("This is a sentence."), 6);
}