java o(n) solution considering uppercase and lowercase


  • 0
    S

    This method considers letters can be shown in ASCII, and the problem did not mention if it is lowercase or uppercase, so create big enough array and the value in array means the occurrence of the letter

    public class Solution {
        public boolean canConstruct(String ransomNote, String magazine) {
            int[] array = new int[256];
            for(int i = 0; i < magazine.length(); i++){
                array[magazine.charAt(i)-'a'] ++;
            }
            for(int i = 0; i < ransomNote.length(); i++){
                if(-- array[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.