2023. 连接后等于目标字符串的字符串对

106 阅读1分钟

这是我参与11月更文挑战的第11天,活动详情查看:2021最后一次更文挑战

2023. 连接后等于目标字符串的字符串对

给你一个 数字 字符串数组 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 。

1636769466(1).png

解题思路

  1. 使用map记录每个字符串出现的下标,因为可能存在相同的字符串出现在不同下标,因此下标使用vector进行维护
  2. 遍历所有字符串,假设其组成的是target的前部分,使用map快速判断是否存在其他下标的字符串可以组成target的后部分

例如对于第一个样例:

nums = ["777","7","77","77"], target = "7777"
  1. 对于nums[0]=“777”,map中存在“7”可以与其构成“7777”,并且下标与其不相等
  2. 对于nums[1]=“7”,map中存在“777”可以与其构成“7777”,并且下标与其不相等
  3. 对于nums[2]=“77”,map中存在“77”可以与其构成“77”,只存在一个下标与其不相等,所以答案只能加一
  4. 对于nums[3]=“777”,map中存在“77”可以与其构成“77”,只存在一个下标与其不相等,所以答案只能加一

代码

class Solution {
public:
    int numOfPairs(vector<string>& nums, string target) {
        map<string,vector<int>> m;
        for (int i = 0; i < nums.size(); ++i) {
            m[nums[i]].push_back(i);
        }
        int res(0);
        for (int i = 0; i < nums.size(); ++i) {
            if (target.size()<nums[i].size())
                continue;
            string front= target.substr(0,nums[i].size());
            string back=target.substr(nums[i].size(),target.size()-nums[i].size());
            if (nums[i]==front&&m.count(back)){
                for(auto t:m[back])
                    if (t!=i)
                        res++;
            }
        }
        return res;
    }
};