给你一个?数字?字符串数组?nums ?和一个?数字?字符串?target ?,请你返回?nums[i] + nums[j] ?(两个字符串连接)结果等于?target ?的下标?(i, j) ?(需满足?i != j )的数目。
示例 1:
输入:nums = ["777","7","77","77"], target = "7777"
输出:4
解释:符合要求的下标对包括:
- (0, 1):"777" + "7"
- (1, 0):"7" + "777"
- (2, 3):"77" + "77"
- (3, 2):"77" + "77"
示例 2:
输入:nums = ["123","4","12","34"], target = "1234"
输出:2
解释:符合要求的下标对包括
- (0, 1):"123" + "4"
- (2, 3):"12" + "34"
示例 3:
输入:nums = ["1","1","1"], target = "11"
输出:6
解释:符合要求的下标对包括
- (0, 1):"1" + "1"
- (1, 0):"1" + "1"
- (0, 2):"1" + "1"
- (2, 0):"1" + "1"
- (1, 2):"1" + "1"
- (2, 1):"1" + "1"
提示:
2 <= nums.length <= 100 1 <= nums[i].length <= 100 2 <= target.length <= 100 nums[i] ?和?target ?只包含数字。nums[i] ?和?target ?不含有任何前导 0 。
C++
class Solution {
public:
int numOfPairs(vector<string>& nums, string target) {
unordered_map<string,int> mp;
for(auto num:nums) {
mp[num]++;
}
int n=target.size();
int res=0;
for(int i=0;i<n-1;i++) {
string a=target.substr(0,i+1);
string b=target.substr(i+1);
if(mp.find(a)!=mp.end() && mp.find(b)!=mp.end()) {
if(a==b) {
res+=mp[a]*(mp[b]-1);
} else {
res+=mp[a]*mp[b];
}
}
}
return res;
}
};
java
class Solution {
public int numOfPairs(String[] nums, String target) {
Map<String, Integer> mp = new HashMap<>();
for (String num : nums) {
mp.put(num, mp.getOrDefault(num, 0) + 1);
}
int n = target.length();
int res = 0;
for (int i = 0; i < n-1; i++) {
String a = target.substring(0, i + 1);
String b = target.substring(i + 1, n);
if (mp.containsKey(a) && mp.containsKey(b)) {
if(a.equals(b)) {
res+=mp.get(a)*(mp.get(b)-1);
} else {
res+=mp.get(a)*mp.get(b);
}
}
}
return res;
}
}
python
class Solution:
def numOfPairs(self, nums: List[str], target: str) -> int:
res = 0
ct = Counter()
n = len(target)
for num in nums:
ct[num] += 1
for i in range(n):
a = target[0:i + 1]
b = target[i + 1:]
if a in ct and b in ct:
if a == b:
res += ct[a] * (ct[b] - 1)
else:
res += ct[a] * ct[b]
return res
|