user1188938
user1188938

Reputation: 125

can i fill a used hashmap with zeros after its been used? C programming

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?

Upvotes: -1

Views: 61

Answers (2)

sgargoyle777
sgargoyle777

Reputation: 1

i think you may be a little confused, the continue keyword is kinda useless as it forces the next iteration, thing that would happen anyway.

The while guard is not modified, and with no break or return you are basically looping forever if you enter the while block.

The hashmap can be set to zero with a memset, and probably you want to subtract the character '0' instead of the '\0', but at the same time if you are making the hashmap big 256, you don't need an hashing function, you can just use the character as the index.

Upvotes: 0

Vlad from Moscow
Vlad from Moscow

Reputation: 311126

To set to zeroes the character array hist you can use standard C function memset declared in header <string.h>

#include <string.h>

//...

memset( hist, 0, sizeof( hist ) );

Nevertheless your code is incorrect.

The while loop is infinite if a passed string is not an empty string because the pointer s is not changed within the loop.

The type char can behave as type signed char. That is a string can contain negative codes. In this case a negative index will be used to access the array hist that results in undefined behavior. You need to cast characters to type unsigned char to 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

"abcdaefg"

The character 'a' is found the second time in the position 4. The first character 'a' is in the position 0. So the next substring starts from the position 1 and it will be the longest substring "bcdaefg".

Upvotes: 0

Related Questions