[LeetCode]383. 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

难度

Easy

方法

遍历2个字符串,索引分别为i, j,如果ransomNote[i] == magazine[j],则i++, j++,否则j++。如果i == len(ransomNote),则表示能够用magazine的字符组成ransomNote,否则则不能

python代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution(object):
def canConstruct(self, ransomNote, magazine):
ransomNote = sorted(ransomNote)
magazine = sorted(magazine)

i = 0
j = 0
while i < len(ransomNote) and j < len(magazine):
if ransomNote[i] == magazine[j]:
j += 1
i += 1
else:
j += 1

if i == len(ransomNote):
return True
return False

assert Solution().canConstruct("a", "b") == False
assert Solution().canConstruct("aa", "ab") == False
assert Solution().canConstruct("aa", "aab") == True
assert Solution().canConstruct("djfjfhjf", "aaigcbiafifghhdihcfdjjej") == True