File tree Expand file tree Collapse file tree 1 file changed +26
-4
lines changed
0003_longest_substring_without_repeat Expand file tree Collapse file tree 1 file changed +26
-4
lines changed Original file line number Diff line number Diff line change 22#include <stdlib.h>
33#include <string.h>
44
5-
5+ /* algorithm: very intrasparent.
66int lengthOfLongestSubstring(char *s)
77{
88 int count[256] = {0};
99 int len = 0;
1010 int i, j;
1111
1212 for (i = 0, j = 0; s[i] != '\0'; i++) {
13- count [s [i ]]++ ;
14- while (count [s [i ]] > 1 ) {
15- len = i - j > len ? i - j : len ;
13+ count[s[i]]++; // increase this first char counter, expanding the string
14+ while (count[s[i]] > 1) { // if last char of window becomes duplicate after the move
15+ len = ( i - j > len) ? ( i - j) : len; //
1616 count[s[j++]] -= 1;
1717 }
1818 }
1919
2020 return i - j > len ? i - j : len;
21+ } */
22+ // simplified version
23+ int lengthOfLongestSubstring (char * s ) {
24+ int count [256 ] = {0 }; // 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+
36+ // Update the maximum length of the valid window
37+ len = (i - j + 1 > len ) ? (i - j + 1 ) : len ;
38+ }
39+
40+ return len ;
2141}
2242
43+
44+
2345int main (int argc , char * * argv )
2446{
2547 if (argc != 2 ) {
You can’t perform that action at this time.
0 commit comments