383_ransom_note.cpp 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. //
  2. // Created by Li Zhilong on 11/6/21.
  3. //
  4. //Given two stings ransomNote and magazine, return true if ransomNote can be constructed from magazine and false otherwise.
  5. //
  6. //Each letter in magazine can only be used once in ransomNote.
  7. //
  8. //Example 1:
  9. //Input: ransomNote = "a", magazine = "b"
  10. //Output: false
  11. //
  12. //Example 2:
  13. //Input: ransomNote = "aa", magazine = "ab"
  14. //Output: false
  15. //
  16. //Example 3:
  17. //Input: ransomNote = "aa", magazine = "aab"
  18. //Output: true
  19. #include <unordered_map>
  20. #include <string>
  21. #include <vector>
  22. #include <iostream>
  23. using namespace std;
  24. class Solution
  25. {
  26. public:
  27. bool canConstruct(string ransomNote, string magazine)
  28. {
  29. std::unordered_map<char, int> table;
  30. cout << "Mag size " << magazine.size() << endl;
  31. for (int i = 0; i < magazine.size(); i++)
  32. table.emplace(magazine[i], table[magazine[i]]++);
  33. // for (auto &x: table)
  34. // std::cout << x.first << ": " << x.second << std::endl;
  35. for (int i = 0; i < ransomNote.size(); i++)
  36. {
  37. table[ransomNote[i]] = --table[ransomNote[i]];
  38. if (table[ransomNote[i]] < 0)
  39. return false;
  40. }
  41. return true;
  42. }
  43. bool canConstruct_vec(string ransomNote, string magazine)
  44. {
  45. std::vector<int> table(26);
  46. for (int i=0; i<magazine.size(); i++)
  47. {
  48. table[(int)magazine[i]-(int)'a'] += 1;
  49. }
  50. for (int i=0; i<ransomNote.size();i++)
  51. {
  52. table[(int)ransomNote[i]-(int)'a'] -= 1;
  53. if (table[(int)ransomNote[i]-'a']<0)
  54. {
  55. return false;
  56. }
  57. }
  58. return true;
  59. }
  60. };
  61. int main()
  62. {
  63. Solution s;
  64. string ransomNote = "abagc";
  65. string magazine = "baagggs";
  66. bool can;
  67. can = s.canConstruct_vec(ransomNote, magazine);
  68. cout << "Can? " << can << endl;
  69. }