Java concise solution using one array


  • 2

    Use 1 array to act as hashMap so we can get all the occurrence of letters.

    public boolean canConstruct(String ransomNote, String magazine) {
            int[] cnt = new int[26];
            for(char c: magazine.toCharArray()){
                cnt[c-'a']++;
            }
            
            for(char c: ransomNote.toCharArray()){
                if(--cnt[c-'a']<0)
                    return false;
            }
            return true;
        }
    
    

  • 0
    K

    Could you please explain what your for loops are doing, specifically cnt[c-'a']++ and if(--cnt[c-'a']<0). I don't understand what's happening there.


  • 0
    This post is deleted!

  • 0

    @Kaikai17
    The ++ is counting the characters in magazine, the -- is counting down the same character in the ransomNote, if the count is <0 after --, then there must be at least one character in ransomNote that appears more times than magazine, then we can't construct ransomNode using magazine (because Each 
letter
 in
 the
 magazine 
string 
can
 only 
be
 used 
once
 in
 your 
ransom
 note.

    The c-'a' is just to reduce the size of the array.


  • 0
    K

    @keZhenxu Thanks!


Log in to reply
 

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