[Leetcode] Ransom Note

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.