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.
Solution
For the given magazine string maintain Map of Character and frequency of it. Iterate ransom note string and check if character is present in map or not. If its present just decrease the frequency in map and continue.
Code
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
import java.util.HashMap; import java.util.Map; public class RansomNote { public boolean canConstruct(String r, String m) { Map<Character,Integer> map=new HashMap<Character,Integer>(); for(int i=0;i<m.length();i++){ map.put(m.charAt(i),(map.getOrDefault(m.charAt(i),0)+1)); } for(int i=0;i<r.length();i++){ if(map.containsKey(r.charAt(i))){ if(map.get(r.charAt(i))<=0) return false; }else{ return false; } map.put(r.charAt(i),(map.get(r.charAt(i))-1)); } return true; } public static void main(String[] args) { RansomNote rn=new RansomNote(); System.out.println(rn.canConstruct("aa","aab")); } } |
Output
We encourage you to write a comment if you have a better solution or having any doubt on the above topic.