Simple O(n) java solution


  • 0
    A

    '''
    public class Solution {
    public boolean canConstruct(String ransomNote, String magazine) {
    int[] mag = new int[26];
    for(char c: magazine.toCharArray())
    mag[c-'a']++;

        for(char c: ransomNote.toCharArray() )
            mag[c-'a']--;
        
        for(int i=0;i<26;i++){
            if(mag[i] < 0) return false;
        }
        return true;
    }
    

    }

    '''


  • 0
    A

    @ani13492 Beats 88% of entries


  • 0
    2

    formatted:

    public class Solution {
        public boolean canConstruct(String ransomNote, String magazine) {
            int[] mag = new int[26];
            for(char c: magazine.toCharArray())
                mag[c-'a']++;
    
            for(char c: ransomNote.toCharArray() )
                mag[c-'a']--;
        
            for(int i=0;i<26;i++){
                if(mag[i] < 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.