Use HashMap to solve--Java


  • 0
    L
    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),map.get(magazine.charAt(i)) + 1);
                    continue;
                }
                map.put(magazine.charAt(i),0);
            }
            for (int i = 0; i < ransomNote.length(); i++) {
                if (map.containsKey(ransomNote.charAt(i))){
                    if (map.get(ransomNote.charAt(i)) == 0) {
                        map.remove(ransomNote.charAt(i));
                    }else{
                        int temp = map.get(ransomNote.charAt(i)) - 1;
                        map.put(ransomNote.charAt(i),temp);
                    }
                    
                }else{
                    return false;
                }
            }
            return true;
        }
    }
    

Log in to reply
 

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