leetcode 383. Ransom Note HashMap查询加速

来源:互联网 发布:李强强 php 编辑:程序博客网 时间:2024/06/06 21:01

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.

canConstruct(“a”, “b”) -> false
canConstruct(“aa”, “ab”) -> false
canConstruct(“aa”, “aab”) -> true

直接使用HashMap遍历即可。

代码如下:

import java.util.HashMap;import java.util.Map;class Solution {    public boolean canConstruct(String ransomNote, String magazine)     {        if(ransomNote==null || magazine==null || ransomNote.length()>magazine.length())            return false;        Map<Character, Integer> map=new HashMap<>();        for(int i=0;i<magazine.length();i++)            map.put(magazine.charAt(i), map.getOrDefault(magazine.charAt(i), 0)+1);             for(int i=0;i<ransomNote.length();i++)        {            if(map.containsKey(ransomNote.charAt(i))==false)                return false;            else             {                int size=map.get(ransomNote.charAt(i));                if(size==1)                    map.remove(ransomNote.charAt(i));                else                     map.put(ransomNote.charAt(i), size-1);            }        }        return true;    }}