题目链接 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.
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:
- You may assume that both strings contain only lowercase letters.
题意
-
看字符串
ransomNote能否被字符串magazine构造出来,magazine中的每个字符只允许被使用一次 -
字符串中仅包含小写字母
思路1
- 使用一个哈希表记录下
magazine中每个字符出现次数 - 遍历
ransomNote中每个字符,每次将哈希表中的次数减1,若出现减完之后的结果小于0,则显然不符,否则可以。
代码1
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
int cnt[26] = {0};
for(const auto &it : magazine)
cnt[it - 'a']++;
bool ans = true;
for(const auto &it : ransomNote)
{
if(cnt[it - 'a'])
cnt[it - 'a']--;
else
{
ans = false;
break;
}
}
return ans;
}
};
本文介绍了一种解决勒索信问题的算法,通过使用哈希表记录杂志字符串中每个字符的出现次数,检查是否能完全构造出勒索信字符串。文章详细解释了算法思路与实现过程,并提供了具体代码示例。
1157

被折叠的 条评论
为什么被折叠?



