判断ransom中的字符是否能由magazine中的字符组成(1次) Ransom Note

问题:string

Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false.hash

Each letter in the magazine string can only be used once in your ransom note.it

Note:
You may assume that both strings contain only lowercase letters.io

canConstruct("a", "b") -> false
canConstruct("aa", "ab") -> false
canConstruct("aa", "aab") -> true

解决:table

【注】题目要求是判断ransom中的字符是否能由magazine中的字符组成,而且每一个字符都只能使用1次。function

① 我使用了hash table保存magazine中的字符,而后进行比较便可。class

public class Solution {//14ms
    public boolean canConstruct(String ransomNote, String magazine) {
        int hash[] = new int[256];
        int count = 0;
        for (char c : magazine.toCharArray() ) {
            hash[c] ++;
        }
        for (char c : ransomNote.toCharArray() ) {
            if(hash[c] >= 1){
                count ++;
                hash[c] --;
            }else{
                return false;
            }
        }
        return count == ransomNote.length();
    }
}效率

进化版:sed

public class Solution {//13ms
    public boolean canConstruct(String ransomNote, String magazine) {  
        int[] hash = new int[26]; 
        for(char c : magazine.toCharArray())hash[c-'a']++; 
        for(char c : ransomNote.toCharArray()){
            hash[c-'a'] --;
            if(hash[c-'a'] < 0) return false;//修改判断条件,效率更高
        }
        return true;
    }
}tab

相关文章
相关标签/搜索