im asked to build a function that finds the longest substring with no repeating characters in a given string.
this is gonna be a 2 in 1 question bc i want to now if my approach is correct and if "emptying" a hashmap is possible.i used this code:
int lengthOfLongestSubstring(char * s){
int hist[256] = {0};
int count = 0;
int max_count = 0;
while(*s){
hist[*s - '\0']++;
if (hist[*s - '\0'] > 1 ){
//fill hist with zeros to start counting again
max_count = count - 1;
count = 0;
continue;
}
}
return max_count;
}
this code would work if i can refill the used hashmap with zeros, its possible with a loop but that sound counter productive, is there another way? and is that even a right approach for the question?
To set to zeroes the character array
histyou can use standard C functionmemsetdeclared in header<string.h>Nevertheless your code is incorrect.
The while loop is infinite if a passed string is not an empty string because the pointer
sis not changed within the loop.The type
charcan behave as typesigned char. That is a string can contain negative codes. In this case a negative index will be used to access the arrayhistthat results in undefined behavior. You need to cast characters to typeunsigned charto access elements of the array.Also take into account that if a duplicated character was encountered then the next substrings starts from the poition that is next to the positon of the frst duplicated character. To make it clear consider the following string
The character 'a' is found the second time in the position
4. The first character 'a' is in the position0. So the next substring starts from the position1and it will be the longest substring"bcdaefg".