Naive but concise Java solution


  • 0
    C

    The time complexity might be O(n) right? where n is the sum of ransom length and magazine length.

    public class Solution {
        public boolean canConstruct(String ransomNote, String magazine) {
            int[] chars = new int[26];
            // count the number of chars in magazine
            for(int i=0;i<magazine.length();i++){
                chars[magazine.charAt(i)-'a']++;
            }
           // decrease count when it occurs in ransom, once a char has count less than 0 return false
            for(int i=0;i<ransomNote.length();i++){
                if(--chars[ransomNote.charAt(i)-'a']<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.