29ms C solution beats 100%


  • 0
    V

    The idea: Keep a character pointer for each dictionary word. Iterating the string, if the current character matches one dictionary word's pointed character, forward the pointer. Pick the longest dictionary word (or lexicographically smaller) whose pointer reaches the end.

    char* findLongestWord(char* s, char** d, int dSize)
    {
        if (!(*s) || dSize == 0)
            return "";
    
        int len[dSize], i, lenmax;
        char* result;
    
        memset(len, 0, sizeof(len));
        lenmax = 0;
        result = "";
    
        for (; *s != '\0'; s++)
            for (i = 0; i < dSize; i++)
                if (*d[i] == *s) {
                    d[i]++;
                    len[i]++;
                }
    
        for (i = 0; i < dSize; i++)
            if (*d[i] == '\0' && (*result == '\0' || len[i] > lenmax || (len[i] == lenmax && strcmp(result, d[i] - len[i]) > 0))) {
                lenmax = len[i];
                result = d[i] - len[i];
            }
    
        return result;
    }
    

Log in to reply
 

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