File tree Expand file tree Collapse file tree 1 file changed +21
-1
lines changed
0003_longest_substring_without_repeat Expand file tree Collapse file tree 1 file changed +21
-1
lines changed Original file line number Diff line number Diff line change @@ -4,7 +4,7 @@ using namespace std;
44
55class Solution {
66public:
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};
You can’t perform that action at this time.
0 commit comments