题目:
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
翻译:
随意给定一封勒索信的字符串和另外一个包含杂志中所有字符的字符串,写下一个函数可以返回 真 如果这封勒索信可以从杂志中构建出来;否则,它将返回 假 。
在杂志字符串中的每一个字符只能在勒索信中使用一次。
注意:
你可以假定这两者的字符串中只包含小写字母。
扫描二维码关注公众号,回复:
940718 查看本文章
canConstruct("a", "b") -> false canConstruct("aa", "ab") -> false canConstruct("aa", "aab") -> true
思路:
这道题代码不难,难在理解题目,题目所说的到底是什么意思,通俗来讲,就是说要保证组成勒索信中的每个字符的种类和个数要小于等于杂志中的字符的种类和个数,才算作勒索信可以从杂志中构建出来,返回 真;否则,勒索信不能从杂志中构建出来,返回 假。这样一来,就很容易编程实现了,用一个映射map来映射杂志中的所有字符种类和字符出现个数,然后再用这个map去匹配勒索信中的字符种类和个数。
C++代码(Visual Studio 2017):
#include "stdafx.h" #include <iostream> #include <string> #include <map> using namespace std; class Solution { public: bool canConstruct(string ransomNote, string magazine) { map<char, int> m; for (int i = 0; i < magazine.size(); i++) { m[magazine[i]]++; } for (int i = 0; i < ransomNote.size(); i++) { if (--m[ransomNote[i]] < 0) return false; } return true; } }; int main() { Solution s; string ransomNote = "aa"; string magazine = "ab"; bool result; result = s.canConstruct(ransomNote, magazine); cout << result; return 0; }