目录
题目
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.
Example:
canConstruct(“a”, “b”) -> false
canConstruct(“aa”, “ab”) -> false
canConstruct(“aa”, “aab”) -> trueNote:
You may assume that both strings contain only lowercase letters.
解决方案
1 | public class Solution { |
注意事项
- 先判断特殊情况,如果magazine的长度比ransomNote小,那么一定不能组成结果。
- 将magazine的每个字符存入list备用。
- 遍历ransomNote,将每个字符从list中弹出,如果成功,证明list中有这个字符,也就是能作为构成ransomNote的一个字符,如果弹出失败,说明没有这个字符,返回false即可。