A very typical application of hash maps. Since I am now learning Java, I code in Java. The following code uses ToCharArray () and Getordefault (), which is learnt from this post.
Public classSolution { Public Booleancanconstruct (String ransomnote, String magazine) {HashMap<character, integer> map =NewHashmap<>(); for(Character K:magazine.tochararray ()) {intv = map.getordefault (k, 0) + 1; Map.put (k, v); } for(Character K:ransomnote.tochararray ()) {intv = map.getordefault (k, 0)-1; if(v < 0)return false; Map.put (k, v); } return true; }}
This code takes is about 60ms.
In fact, arrays can is used to replace hash maps since the test cases of this problem only contan the Chinese letters. A array-version solution can be found here and is rewritten below.
Public classSolution { Public Booleancanconstruct (String ransomnote, String magazine) {int[] Map =New int[26]; for(CharK:magazine.tochararray ()) Map[k-' A ']++; for(CharK:ransomnote.tochararray ()) { intv =--map[k-' a ']; if(v < 0)return false; } return true; }}
This version was much faster, about 13MS.
[Leetcode] Ransom Note