[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;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章