Java O(n+m) solution


  • 0
    V
        public boolean canConstruct(String ransomNote, String magazine) {
            
            int ransom_length = ransomNote.length();
            int magazine_length = magazine.length();
            int index = 0;
            
            if(ransom_length > magazine_length)
                return false;
            
            int hash_letter_cnt[] = new int[26];
            
            for(int i=0;i<magazine_length;++i)
            {
                ++hash_letter_cnt[magazine.charAt(i)-'a'];
            }
            
            for(int i=0;i<ransom_length;++i)
            {
                index = ransomNote.charAt(i)-'a';
                --hash_letter_cnt[index];
                
                if(hash_letter_cnt[index] < 0)
                    return false;
            }
            
            return true;
        }
    }
    

Log in to reply
 

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