Skip to content

Commit cc59c03

Browse files
authored
Update longest_substring_without_repeat.cc
shorter ver
1 parent 597ada1 commit cc59c03

File tree

1 file changed

+21
-1
lines changed

1 file changed

+21
-1
lines changed

0003_longest_substring_without_repeat/longest_substring_without_repeat.cc

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ using namespace std;
44

55
class Solution {
66
public:
7-
int lengthOfLongestSubstring(string s) {
7+
/*int lengthOfLongestSubstring(string s) {
88
vector<int> count(256);
99
int len = 0;
1010
int i, j;
@@ -18,5 +18,25 @@ class Solution {
1818
}
1919
2020
return i - j > len ? i - j : len;
21+
}*/
22+
23+
int lengthOfLongestSubstring(char *s) {
24+
vector<int> count(256); // Frequency of characters
25+
int len = 0; // Longest substring length
26+
int i = 0, j = 0; // Sliding window pointers
27+
28+
for (i = 0; s[i] != '\0'; i++) {
29+
count[s[i]]++; // Add s[i] to the window
30+
31+
// If a duplicate is introduced, shrink the window
32+
if (count[s[i]] > 1) {
33+
count[s[j++]]--; // Remove the character at s[j] and move j forward
34+
}
35+
// Update the maximum length of the valid window
36+
len = (i - j + 1 > len) ? (i - j + 1) : len;
37+
}
38+
39+
return len;
2140
}
41+
2242
};

0 commit comments

Comments
 (0)