-
Notifications
You must be signed in to change notification settings - Fork 0
/
canConstruct.py
72 lines (66 loc) · 1.79 KB
/
canConstruct.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#Source : https://leetcode.com/problems/ransom-note/
#Author : Yuan Wang
#Date : 2018-06-23
'''
**********************************************************************************
*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
**********************************************************************************/
'''
#Self solution A,Time complexity:O(n), Space Complexity:O(n)
def canConstructA(ransomNote, magazine):
"""
:type ransomNote: str
:type magazine: str
:rtype: bool
"""
magazine=dict(collections.Counter(magazine))
ransomNote=dict(collections.Counter(ransomNote))
for i in ransomNote:
try:
if ransomNote[i] > magazine[i]:
return False
except:
return False
return True
#Self solution B,Time complexity:O(n), Space Complexity:O(n)
def canConstructB(ransomNote, magazine):
"""
:type ransomNote: str
:type magazine: str
:rtype: bool
"""
magazine=dict(collections.Counter(magazine))
for i in ransomNote:
if i in magazine:
if magazine[i] > 0:
magazine[i]-=1
else:
return False
else:
return False
return True
#Other suliton using set
def canConstruct(ransomNote, magazine):
"""
:type ransomNote: str
:type magazine: str
:rtype: bool
"""
for i in set(ransomNote):
if ransomNote.count(i) > magazine.count(i):
return False
return True
ransomNote="aa"
magazine="aab"
print(canConstruct(ransomNote,magazine))