I am trying to solve the longest substring problem. Below one is my code and there is a serious bug in it and I couldn't find it.
I have spend too much time to find it but couldn't succeed.
#include <stdio.h>
int lengthOfLongestSubstring(char * s){
int i = 0;
char arr[255];
int max = 0;
memset(arr, -1, 255);
int si = 0; //substring start index
while(s[i] != '\0'){
if (arr[s[i]] != -1){
int psi = si; //previous substring start
int pi = arr[s[i]]; //previous index of s[i]
si = pi + 1; //new substring starts
int psl = i - psi; //previous substring length
max = max>psl?max:psl;
for(int j=psi;j<=pi;j++){
arr[s[j]] = -1;
}
}
arr[s[i]] = i;
i++;
}
max = max>(i-si)?max:(i-si);
return max;
}
int main(int argc, char **argv)
{
//printf("%s\n", argv[1]);
printf("%d\n", lengthOfLongestSubstring(argv[1]));
return 0;
}
It gives me runtime error for the input "hijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789hijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789hijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789hijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789hijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789hijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"