C++ solution - 26 ms

  • 0

    I used the following approach:

    1. Starting from the first element of ransomNote, check if element 'i' in string ransomNote is present in string magazine
    2. If found, then copy the last element of string magazine at location given by "iterator p" and pop out the last element of string magazine
    3. If not found then you cannot construct the message, so just return false
    4. If you are able to iterate through all the elements of ransomNote then it implies that you can construct the message, so return true at the end.

    bool Solution::canConstruct(string ransomNote, string magazine)
    string::iterator p = magazine.begin();

     for(unsigned int i = 0; i < ransomNote.size(); i++)
        p = find(magazine.begin(), magazine.end(), ransomNote[i]);
        if(p == magazine.end())
            return false;
        *p = magazine[magazine.size() - 1];
    return true;


Log in to reply

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