一、题目
Given two strings ransomNote and magazine, return true if ransomNote can be constructed by using the letters from magazine and false otherwise.
Each letter in magazine can only be used once in ransomNote.
Example 1:
Input: ransomNote = “a”, magazine = “b”
Output: false
Example 2:
Input: ransomNote = “aa”, magazine = “ab”
Output: false
Example 3:
Input: ransomNote = “aa”, magazine = “aab”
Output: true
Constraints:
1 <= ransomNote.length, magazine.length <= 105
ransomNote and magazine consist of lowercase English letters.文章来源:https://www.toymoban.com/news/detail-713736.html
二、题解
使用数组模拟哈希表解决文章来源地址https://www.toymoban.com/news/detail-713736.html
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
int n1 = ransomNote.length();
int n2 = magazine.length();
vector<int> chars(26,0);
for(int i = 0;i < n2;i++){
chars[magazine[i] - 'a']++;
}
for(int i = 0;i < n1;i++){
if(chars[ransomNote[i] - 'a'] == 0) return false;
chars[ransomNote[i] - 'a']--;
}
return true;
}
};
到了这里,关于LeetCode383. Ransom Note的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!