forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
number-of-pairs-of-strings-with-concatenation-equal-to-target.py
50 lines (43 loc) · 1.44 KB
/
number-of-pairs-of-strings-with-concatenation-equal-to-target.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
# Time: O(n * l), n is the size of nums, l is the average length of the digit string in nums
# Space: O(n)
import collections
class Solution(object):
def numOfPairs(self, nums, target):
"""
:type nums: List[str]
:type target: str
:rtype: int
"""
lookup = collections.Counter()
result = 0
for num in nums:
cnt1, cnt2 = lookup[-(len(target)-len(num))], lookup[len(target)-len(num)]
if target.startswith(num):
result += cnt1
lookup[len(num)] += 1
if target.endswith(num):
result += cnt2
lookup[-len(num)] += 1
return result
# Time: O(n * l), n is the size of nums, l is the average length of the digit string in nums
# Space: O(n)
import collections
class Solution2(object):
def numOfPairs(self, nums, target):
"""
:type nums: List[str]
:type target: str
:rtype: int
"""
prefix, suffix = collections.Counter(), collections.Counter()
result = 0
for num in nums:
if target.startswith(num):
result += suffix[len(target)-len(num)]
if target.endswith(num):
result += prefix[len(target)-len(num)]
if target.startswith(num):
prefix[len(num)] += 1
if target.endswith(num):
suffix[len(num)] += 1
return result