java solution with hashmap


  • 0
    P

    public class Solution {
    public boolean canConstruct(String ransomNote, String magazine) {
    HashMap<Character,Integer> map = new HashMap<Character,Integer>();
    for(int i = 0;i<magazine.length();i++)
    {
    if(!map.containsKey(magazine.charAt(i)))
    {
    map.put(magazine.charAt(i),1);
    }
    else
    {
    map.put(magazine.charAt(i),map.get(magazine.charAt(i))+1);
    }
    }
    for(int i = 0;i<ransomNote.length();i++)
    {
    if(map.containsKey(ransomNote.charAt(i)))
    {
    map.put(ransomNote.charAt(i),map.get(ransomNote.charAt(i))-1);
    }
    else
    {
    return false;
    }
    }
    List<Integer> list = new ArrayList<Integer>(map.values());
    for(int num:list)
    {
    if(num<0)
    {
    return false;
    }
    }
    return true;
    }
    }


  • 0
    N

    it would be better if you could format the code with ''' .

    For more detail, please read from : (i.e. read the instructions)

    https://discuss.leetcode.com/topic/22/welcome-new-users-please-read-this-before-posting


  • 0
    M
        public boolean canConstruct(String ransomNote, String magazine) {
            HashMap<Character,Integer> map = new HashMap<Character,Integer>();
            for(int i = 0;i<magazine.length();i++)
            {
                if(!map.containsKey(magazine.charAt(i)))
                {
                    map.put(magazine.charAt(i),1);
                }
                else
                {
                    map.put(magazine.charAt(i),map.get(magazine.charAt(i))+1);
                }
            }
            for(int i = 0;i<ransomNote.length();i++)
            {
                if(map.containsKey(ransomNote.charAt(i)))
                {
                    map.put(ransomNote.charAt(i),map.get(ransomNote.charAt(i))-1);
                }
                else
                {
                    return false;
                }
            }
            List<Integer> list = new ArrayList<Integer>(map.values());
            for(int num:list)
            {
                if(num<0)
                {
                    return false;
                }
            }
            return true;
        }
    }
    
    This one with indentation is easy to read. Remember to use ``` before posting your code.

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.