Does anyone have better C solution? Time Limit Exceed

  • 0

    bool wordBreak(char* s, char** wordDict, int wordDictSize) {
    int i;
    int WordLength;

    for (i = 0; i < wordDictSize; i++){
        WordLength = strlen(wordDict[i]);
        if (memcmp(s, wordDict[i], WordLength) == 0){
            if (strlen(s+WordLength) != 0) {
                if (wordBreak(s+WordLength, wordDict, wordDictSize)){ return true;}
                return true;
    return false;


  • 1

    Dynamic programming:

    Create a set ( a hash set is the best, or at least a list ) to record each sub-string that failed to break by the dictionary, and when you meet that sub-string again, just check the set and no need to do recursion again.

Log in to reply

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