18ms JAVA O(n) 11 Line Solution - Hash Table


  • 0

    Just use a hash table to record the characters from magazine, and then check whether the character is enough.

    public class Solution {
        public boolean canConstruct(String ransomNote, String magazine) {
            int[] hash = new int[26];
            for(int i = 0; i < ransomNote.length(); i++)hash[ransomNote.charAt(i) - 'a']--;
            for(int i = 0; i < magazine.length(); i++)hash[magazine.charAt(i) - 'a']++;
            for(int i = 0; i < 26; i++){
                if(hash[i] < 0)return false;
            }
            return true;
        }
    }
    

  • 0
    A

    Are you sure this is a HashTable solution?


Log in to reply
 

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