0%

leetcode Ransom Note

leetcode 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.

1
2
3
canConstruct("a", "b") -> false
canConstruct("aa", "ab") -> false
canConstruct("aa", "aab") -> true

题目地址:leetcode Ransom Note

题目大意:给定两个字符串magazines和ransomNote,问是否可以从magazines中抽取字母(每个字母只能用一次)组成ransomNote

思路:只要判断ransomNote字符是不是全部在magazines中即可,用hash。。 水

C++

1
2
3
4
5
6
7
8
9
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
vector<int> cnt(26,0);
for(char x:magazine) cnt[x-97]++;
for(char x:ransomNote) if(--cnt[x-97] < 0) return false;
return true;
}
};

Java

1
2
3
4
5
6
7
8
public class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
int[] cnt = new int[26];
for (int i = 0; i < magazine.length(); i++) cnt[magazine.charAt(i) - 97]++;
for (int i = 0; i < ransomNote.length(); i++) if (--cnt[ransomNote.charAt(i) - 97] < 0) return false;
return true;
}
}

Python

1
2
3
4
5
6
7
8
9
10
11
12
class Solution(object):
def canConstruct(self, ransomNote, magazine):
"""
:type ransomNote: str
:type magazine: str
:rtype: bool
"""
cnt = collections.Counter(magazine)
for letter in ransomNote:
cnt[letter] -= 1
if cnt[letter] <0: return False
return True

 

本题是leetcode 383 Ransom Note 的题解

更多题解可以查看:https://www.hrwhisper.me/leetcode-algorithm-solution/

请我喝杯咖啡吧~