LeetCode - The World's Leading Online Programming Learning Platform
class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
int[] charCounts = new int[26]; // Assuming lowercase English letters
for (char c : magazine.toCharArray()) {
charCounts[c - 'a']++;
}
for (char c : ransomNote.toCharArray()) {
if ( !(charCounts[c - 'a'] > 0 ) ) {
return false;
}
charCounts[c - 'a']--;
}
return true;
}
}
class Solution {
public static boolean canConstruct(String ransomNote, String magazine) {
HashSet<Character> list = new HashSet<>();
for (char c : ransomNote.toCharArray())
list.add(c);
for (Character c : list)
{
int count1 = countChar(ransomNote , c);
int count2 = countChar(magazine , c);
if (count1 > count2)
return false;
}
return true;
}
public static int countChar(String str , char c)
{
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == c) {
count++;
}
}
return count;
}
}
import java.util.Hashtable;
import java.util.Map;
class Solution {
public static boolean canConstruct(String ransomNote, String magazine) {
Hashtable<Character, Integer> list1 = new Hashtable<>();
for (char c : magazine.toCharArray()) {
list1.put(c, list1.getOrDefault(c, 0) + 1);
}
Hashtable<Character, Integer> list2 = new Hashtable<>();
for (char c : ransomNote.toCharArray()) {
list2.put(c, list2.getOrDefault(c, 0) + 1);
}
for (Map.Entry<Character, Integer> entry : list2.entrySet()) {
char c = entry.getKey();
int countNeeded = entry.getValue();
if (!list1.containsKey(c) || list1.get(c) < countNeeded) {
return false;
}
}
return true;
}
}