Count Pairs of Equal Substrings With Minimum Difference
Here’s the Python solution:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
| class Solution:
def countQuadruples(self, firstString: str, secondString: str) -> int:
pos1 = [0] * 26
pos2 = [0] * 26
cnt = 0
j_a = float('inf')
for j in range(len(firstString) - 1, -1, -1):
pos1[ord(firstString[j]) - ord('a')] = j + 1
for a in range(len(secondString)):
pos2[ord(secondString[a]) - ord('a')] = a + 1
for i in range(26):
if pos1[i] and pos2[i]:
if pos1[i] - pos2[i] < j_a:
j_a = pos1[i] - pos2[i]
cnt = 0
cnt += int(pos1[i] - pos2[i] == j_a)
return cnt
|
The code uses two arrays, pos1
and pos2
, to keep track of the last occurrence of each character in the two strings. It then iterates through these arrays and calculates the number of quadruples that meet the conditions, storing the result in cnt
, which is returned.