# # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param ransomNote string字符串 # @param magazine string字符串 # @return bool布尔型 # from collections import Counter class Solution: def canConstruct(self, ransomNote: str, magazine: str) -> bool: # write code here return False if len(ransomNote) > len(magazine) else not (Counter(ransomNote) - Counter(magazine))
return Counter(magazine) >= Counter(ransomNote)如果牛客支持的是python3.10而不是3.9的话,这一行应该够了
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param ransomNote string字符串
* @param magazine string字符串
* @return bool布尔型
*/
public boolean canConstruct (String ransomNote, String magazine) {
// write code her
HashMap<Character, Integer> hmS = new HashMap<>();
HashMap<Character, Integer> hmT = new HashMap<>();
for (int i = 0; i < ransomNote.length(); i++) {
char c = ransomNote.charAt(i);
hmS.put(c, hmS.getOrDefault(c, 0) + 1);
}
for (int j = 0; j < magazine.length(); j++) {
char c = magazine.charAt(j);
hmT.put(c, hmT.getOrDefault(c, 0) + 1);
}
for (Character k : hmS.keySet()) {
if (hmT.containsKey(k) && hmS.get(k) <= hmT.get(k)) {
continue;
} else {
return false;
}
}
return true;
}
} bool canConstruct(string s, string t) {
// write code here
unordered_map<char, int> mp;
for(char i:t){
mp[i]++;
}
for(char i:s){
if(mp[i]) mp[i]--;
else return false;
}
return true;
} class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param ransomNote string字符串
* @param magazine string字符串
* @return bool布尔型
*/
bool canConstruct(string ransomNote, string magazine) {
// write code here
vector<int> v(26, 0);
for(char ch : magazine) v[ch - 'a']++;
for(char ch : ransomNote){
if(v[ch - 'a'] == 0) return false;
v[ch - 'a']--;
}
return true;
}
}; # # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param ransomNote string字符串 # @param magazine string字符串 # @return bool布尔型 # class Solution: def canConstruct(self , ransomNote: str, magazine: str) -> bool: # write code here if len(ransomNote) < len(magazine): for i in list(set(ransomNote)): if i not in list(set(magazine)): return False return True else: return False
#include <unordered_map>
#include <unordered_set>
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
* @param ransomNote string字符串
* @param magazine string字符串
* @return bool布尔型
*/
bool canConstruct(string ransomNote, string magazine) {
int s1 = ransomNote.size();
int count = 0;
unordered_map<char, int> ss;
for(auto c : magazine){ // 先将T串每个字符丢进哈希表,记录其中每种字符的出现次数
ss[c]++;
}
int i = 0;
while (s1) {
if(ss[ransomNote[i]]!=0){ // 遍历s串,看当前字符的出现次数是否有
count ++; // 有就++个数,但表中的次数要减少
ss[ransomNote[i]]--;
}
i++;
s1--;
}
if(count == ransomNote.size()){ // 最后个数和s串一样长,就能构造出来
return true;
}else {
return false;
}
}
};