[LeetCode] Count Pairs of Equal Substrings With Minimum Difference

1794. Count Pairs of Equal Substrings With Minimum Difference

You are given two strings firstString and secondString that are 0-indexed and consist only of lowercase English letters. Count the number of index quadruples (i,j,a,b) that satisfy the following conditions:

  • 0 <= i <= j < firstString.length
  • 0 <= a <= b < secondString.length
  • The substring of firstString that starts at the ith character and ends at the jth character (inclusive) is equal to the substring of secondString that starts at the ath character and ends at the bth character (inclusive).
  • j - a is the minimum possible value among all quadruples that satisfy the previous conditions.

Return the number of such quadruples.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
int countQuadruples(string A, string B) {
unordered_map<char, int> mp;
for(int i = 0; i < B.length(); i++)
mp[B[i]] = i;
int len = INT_MAX, res = 0;
for(int i = 0; i < A.length(); i++) {
if(!mp.count(A[i])) continue;
int clen = i - mp[A[i]];
if(clen == len) res++;
else if(clen < len) {
len = clen;
res = 1;
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/08/01/PS/LeetCode/count-pairs-of-equal-substrings-with-minimum-difference/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.