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.cpp
53 lines (51 loc) · 2.18 KB
/
number-of-pairs-of-strings-with-concatenation-equal-to-target.cpp
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
51
52
53
// Time: O(n * l), n is the size of nums, l is the average length of the digit string in nums
// Space: O(n)
class Solution {
public:
int numOfPairs(vector<string>& nums, string target) {
unordered_map<int, int> lookup;
int result = 0;
for (const auto& num : nums) {
if (size(num) > size(target)) {
continue;
}
const int cnt1 = lookup[-(size(target) - size(num))], cnt2 = lookup[size(target) - size(num)];
if (!target.compare(0, size(num), num)) { // in c++ 20, we can directly use starts_with, see https://en.cppreference.com/w/cpp/string/basic_string/starts_with
result += cnt1;
++lookup[size(num)];
}
if (!target.compare(size(target) - size(num), size(num), num)) { // in c++ 20, we can directly use ends_with, see https://en.cppreference.com/w/cpp/string/basic_string/ends_with
result += cnt2;
++lookup[-size(num)];
}
}
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)
class Solution2 {
public:
int numOfPairs(vector<string>& nums, string target) {
unordered_map<int, int> prefix, suffix;
int result = 0;
for (const auto& num : nums) {
if (size(num) > size(target)) {
continue;
}
if (!target.compare(0, size(num), num)) { // in c++ 20, we can directly use starts_with, see https://en.cppreference.com/w/cpp/string/basic_string/starts_with
result += suffix[size(target) - size(num)];
}
if (!target.compare(size(target) - size(num), size(num), num)) { // in c++ 20, we can directly use ends_with, see https://en.cppreference.com/w/cpp/string/basic_string/ends_with
result += prefix[size(target) - size(num)];
}
if (!target.compare(0, size(num), num)) {
++prefix[size(num)];
}
if (!target.compare(size(target) - size(num), size(num), num)) {
++suffix[size(num)];
}
}
return result;
}
};