Ransom Note – LeetCode 383
Problem
Description
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
You may assume that both strings contain only lowercase letters.
canConstruct(“a”, “b”) -> false
canConstruct(“aa”, “ab”) -> false
canConstruct(“aa”, “aab”) -> true
Answer
Original
Code
1 | class Solution { |
思路
先排序再遍历,做复杂了,但是是常数的空间消耗。时间复杂度$O(log{n})$,空间复杂度$O(1)$。
Better
思路
简单的使用数组来保存出现的次数,用空间换时间。时间复杂度$O(n)$,空间复杂度$O(n)$。
Code
1 | class Solution { |