判斷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

相關文章
相關標籤/搜索