383. Ransom Note

  • 47.2%

https://leetcode.com/problems/ransom-note/

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.

1
2
3
canConstruct("a", "b") -> false
canConstruct("aa", "ab") -> false
canConstruct("aa", "aab") -> true

cpp

89ms, September 13, 2016

https://discuss.leetcode.com/topic/53865/two-ac-c-solutions-unordered_map-vector

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
unordered_map<char, int> map;
for(int i = 0; i < magazine.size(); ++i)
++map[magazine[i]];
for(int j = 0; j < ransomNote.size(); ++j)
if(--map[ransomNote[j]] < 0)
return false;
return true;
}
};

29ms, September 13, 2016

https://discuss.leetcode.com/topic/53865/two-ac-c-solutions-unordered_map-vector

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
vector<int> vec(26, 0);
for (int i = 0; i < magazine.size(); ++i)
++vec[magazine[i] - 'a'];
for (int j = 0; j < ransomNote.size(); ++j)
if (--vec[ransomNote[j] - 'a'] < 0)
return false;
return true;
}
};

python

265ms, September 13, 2016

https://discuss.leetcode.com/topic/53902/o-m-n-one-liner-python

O(m+n) one-liner Python

O(m+n) with m and n being the lengths of the strings.

1
2
3
4
5
6
7
8
class Solution(object):
def canConstruct(self, ransomNote, magazine):
"""
:type ransomNote: str
:type magazine: str
:rtype: bool
"""
return not collections.Counter(ransomNote) - collections.Counter(magazine)

java

24ms, September 13, 2016

https://discuss.leetcode.com/topic/53864/java-o-n-solution-easy-to-understand

Java O(n) Solution—Easy to understand

1
2
3
4
5
6
7
8
9
10
11
12
13
public class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
int[] arr = new int[26];
for(int i = 0; i<magazine.length(); i++){
arr[magazine.charAt(i) - 'a']++;
}
for(int i = 0; i<ransomNote.length(); i++){
if(--arr[ransomNote.charAt(i)-'a'] < 0)
return false;
}
return true;
}
}
谢谢你,可爱的朋友。