25ms accepted C solution. How to make it faster?


  • 0
    V

    Anyone have advice on how to make this solution faster? Simple array of flags of size 128 to keep track of characters seen or not. Scans through input with each character as start of substring to find the longest one.

    #include <string.h>
    int lengthOfLongestSubstring(char* s) {
        int len = strlen(s);
        int max = 0;
        int bank[128];
        memset(bank, 0, 128*sizeof(int));
        int tmpCount = 0;
        int src = 0;
        int scanner = 0;
        while (scanner < len) {
            int index = (int)(s[scanner]);
            if (bank[index] == 0) {
                bank[index] = 1;
                tmpCount++;
                scanner++;
            }
            else {
                if (tmpCount > max) max = tmpCount;
                tmpCount = 0;
                memset(bank, 0, 128*sizeof(int));
                src++;
                scanner = src;
            }
        }
        if (tmpCount > max) max = tmpCount;
        return max;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.