Simple C++ 28ms solution

  • 0
    bool canConstruct(std::string ransomNote, std::string magazine)
      int noteLen = ransomNote.length();
      int magLen = magazine.length();
      //Some special cases to return immediately
      if (magLen < noteLen) return false;
      if (magLen == noteLen && ransomNote==magazine) return true;
      //Since we are only dealing with lowercase letters
      int noteContents[26] = {0};
      int magContents[26] = {0};
      //Each characters count for both strings
      for (int i = 0; i < noteLen; i++) noteContents[ransomNote[i]-'a']++;
      for (int i = 0; i < magLen; i++)  magContents[magazine[i]-'a']++;
      //If ransom string had any character count more than magazine, we can return false
      for (int i = 0; i < 26; i++) if (noteContents[i] > magContents[i]) return false;
      //If nothing has been returned yet, result must be true because we have checked for all false cases
      return true;

    Edit: I agree with @ameyd. Hence removed the initial check to false if both string have same size. Thank you @ameyd

  • 1

    Your solution would fail for canConstruct("ab", "ba"). Expected answer is True.

Log in to reply

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