C 6ms solution


  • 2
    bool canConstruct(char* ransomNote, char* magazine) {
        int len_r = strlen(ransomNote);
        int len_m = strlen(magazine);
        int count_r[26] = {0};
        int count_m[26] = {0};
        int i;
        for(i = 0; i < len_r; ++i) ++count_r[ransomNote[i]-'a'];
        for(i = 0; i < len_m; ++i) ++count_m[magazine[i]-'a'];
        for(i = 0; i < 26; ++i)
            if(count_r[i] > count_m[i]) break;
        if(26 == i) return true;
        return false;
    }
    

  • 0
    S

    why break?"return false" is better?
    for(i = 0; i < 26; ++i)
    if(count_r[i] > count_m[i]) return false;
    return true;


  • 0
    L

    I think it can be improved a little.

    1. We do not need the len_r and len_m.
    2. We do not need the comparison of count array.
    3. We only need one count array.
    int count[26] = {0};
    
    while(*magazine){
        count[*magazine++ - 'a']++;
    }
    while(*ransomNote){
        if(--count[*ransomNote++ - 'a'] < 0)
              return false;
    }
    
    return true;
    
    

Log in to reply
 

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