Four line C++ solution

  • 0

    Runtime: 32ms
    Runtime bound: O(max{n,m})
    Space bound: O(1)

    bool canConstruct(string ransomNote, string magazine) {
        vector<int> V(26,0);
        for (char c : ransomNote) V[c-'a']++;
        for (char c : magazine) V[c-'a']--;
        return all_of(V.begin(), V.end(), [](int i) {return i <= 0;});

  • 1

    Looks pretty complicated. What's the advantage of

    for_each(ransomNote.begin(), ransomNote.end(), [&V](char c) {V[c-'a']++;});


    for (char c : ransomNote) V[c-'a']++;


  • 0

    @StefanPochmann You are right -- I've changed it. Didn't make a difference to runtime, but that does look cleaner.

Log in to reply

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