[383] Ransom Note

1. 題目描述

> 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. 


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

Note:
You may assume that both strings contain only lowercase letters.
canConstruct(“a”, “b”) -> false
canConstruct(“aa”, “ab”) -> false
canConstruct(“aa”, “aab”) -> true

給定一個字符串ransom和一個字符串magazine,判定是否所有ransom中的字符都出現在了magazine裏。

2. 解題思路

讀題真是一大坑。第一次沒讀懂,以爲要包含,所以直接用了字符串的contains函數,然後leetcode給出了不通過的用例。第二次以爲自己懂了,以爲是從magazine中能按順序的匹配出ransom中的字母,結果又會錯意了。第三次才弄明白,只要ransom中的所有字母都出現在magazine中就可以了。第一反應,一個字母一個字母的匹配,但是這個就和magazin的長度直接相關了,而且在處理匹配到的字母之後不能再匹配的問題上不好解決。於是想到了桶排序,先把目標都放在桶裏,之後掃描一遍源,判斷都出現過了的依據就是桶裏的元素全都被消費光了。如ransom=”abcdaaa”,於是我們的桶的樣子就是[4][1][1][1], 如果magazine=”aabbcb”,那麼只要對應位置減掉,桶就變成了[2][-2][0][1],只要發現桶裏有一個大於0的數,就說明magazine中並非包含ransom中的所有元素。Code1用了一個大小爲256的桶,用於處理可能的字符,如果範圍縮小到大小寫字母的話應該能更節省空間,事實證明也通過了所有用例。

3. Code

// Code1:
public class Solution {
    public boolean canConstruct(String ransomNote, String magazine) {
        if(ransomNote.length() > magazine.length()) return false;
        if(ransomNote == null && magazine == null) return true;
        else if("".equals(ransomNote)) return true;
        int[] letter = new int[256];
        for(int i = 0; i < ransomNote.length(); ++i)
        {
            letter[ransomNote.charAt(i)]++;
        }
        for(int j = 0; j < magazine.length(); ++j)
        {
            letter[magazine.charAt(j)]--;
        }
        for(int m = 0; m < 256; ++m)
        {
            if(letter[m] > 0) return false;
        }
        return true;
    }
}
// Code2:縮小桶的容量,假定只包含大小寫字符
public class Solution {
    public boolean canConstruct(String ransomNote, String magazine) {
        if(ransomNote.length() > magazine.length()) return false;
        if(ransomNote == null && magazine == null) return true;
        else if("".equals(ransomNote)) return true;
        int[] letter = new int[52];
        for(int i = 0; i < ransomNote.length(); ++i)
        {
            letter[ransomNote.charAt(i) -'a']++;
        }
        for(int j = 0; j < magazine.length(); ++j)
        {
            letter[magazine.charAt(j) -'a']--;
        }
        for(int m = 0; m < 52; ++m)
        {
            if(letter[m] > 0) return false;
        }
        return true;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章