letecode [383] - Ransom Note
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
题目大意:
判断字符串1能否由字符串2中的字符构成。
理 解:
构建数组记录字符串str2字符的数量,遍历str1,每遍历一个字符,数量减一,当数量减至-1时,返回false.
代 码 C++:
class Solution { public: bool canConstruct(string ransomNote, string magazine) { int hash[26]; for(int i=0;i<26;++i){ hash[i]=0; } for(char v1:magazine){ hash[v1-'a']++; } for(char v2:ransomNote){ hash[v2-'a']--; if(hash[v2-'a']==-1) return false; } return true; } };
运行结果:
执行用时 :20 ms, 在所有 C++ 提交中击败了95.99%的用户
内存消耗 :11 MB, 在所有 C++ 提交中击败了80.00%的用户