[383] Ransom Note
来源:互联网 发布:苹果6电话录音软件 编辑:程序博客网 时间:2024/05/22 01:35
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; }}
- LeetCode:383 Ransom Note
- LeetCode#383 Ransom Note
- [383] Ransom Note
- [383]Ransom Note
- LeetCode 383 Ransom Note
- LeetCode 383:Ransom Note
- Leetcode 383 Ransom Note
- leetcode-383-Ransom Note
- leetcode 383 Ransom Note
- Leetcode #383 Ransom Note
- Leetcode 383 Ransom Note
- LeetCode 383 Ransom Note
- LeetCode[383] Ransom Note
- LeetCode--No.383--Ransom Note
- leetcode 383 Ransom Note C++
- leetcode_c++:Ransom Note(383)
- LeetCode(383)Ransom Note
- 【LeetCode-383】Ransom Note(C++)
- BFS 搜索 写代码思路(顺序)
- 手动实现AOP编程
- 并发控制(3) 使用double check方式的单例,来确保并发下的线程安全的单例模式
- 线程同步问题
- ***完全背包
- [383] Ransom Note
- 同步方法与同步块
- 史上最全最强SpringMVC详细示例实战教程
- redis
- 【GDOI2017模拟8.14】佐助的难题
- Redis3.0 Cluster Redis集群搭建
- HDU 5828-H - Rikka with Sequence-线段树+玄学-区间开方/区间更新/区间求和
- Uva 11552 Fewest Flops
- HDOJ 1325 Is It A Tree?