383. Ransom Note

    xiaoxiao2021-04-12  55

    Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false.

    Each letter in the magazine string can only be used once in your ransom note.

    Note: You may assume that both strings contain only lowercase letters.

    canConstruct("a", "b") -> false canConstruct("aa", "ab") -> false canConstruct("aa", "aab") -> true #include <iostream> #include <string> #include <algorithm> using namespace std; class Solution { public:     bool canConstruct(string ransomNote, string magazine) {         if(ransomNote.length() > magazine.length())         return false;         else         {         for(int i=0;i<ransomNote.length();i++)         {         bool flag = false;         for(int j=0;j<magazine.length();j++)         {         if(ransomNote[i] == magazine[j])         {         magazine[j] = '0';         flag = true;         break; } } if(flag == false) return false; } return true; }     } }; 以下是来自评论区sharmilas的代码 使用了hashmap 截取下来以作参考

    class Solution { public:     bool canConstruct(string ransomNote, string magazine) { int i=0,j=0; map <char ,int> h; while(i<m.length()) { h[m[i]]++; i++; } i=0; while(i<r.length()) { if(h.find(r[i])!=h.end()) { h[r[i]]=h[r[i]]-1; if(h[r[i]]==0) h.erase(h.find(r[i])); } else return false; i++; } return true; } };

    转载请注明原文地址: https://ju.6miu.com/read-667774.html

    最新回复(0)