[LeetCode] Number of Pairs of Strings With Concatenation Equal to Target

2023. Number of Pairs of Strings With Concatenation Equal to Target

Given an array of digit strings nums and a digit string target, return the number of pairs of indices (i, j) (where i != j) such that the concatenation of nums[i] + nums[j] equals target.

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
int numOfPairs(vector<string>& A, string target) {
unordered_map<string, int> freq;
for(auto& a : A) freq[a]++;
int res = 0;
for(int i = 1; i < target.length(); i++) {
string a = target.substr(0,i), b = target.substr(i);
res += freq[a] * (freq[b] - (a == b));
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/08/PS/LeetCode/number-of-pairs-of-strings-with-concatenation-equal-to-target/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.