LeetCode 题解工作台

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

给你一个 数字 字符串数组 nums 和一个 数字 字符串 target ,请你返回 nums[i] + nums[j] (两个字符串连接)结果等于 target 的下标 (i, j) (需满足 i != j )的数目。 示例 1: 输入: nums = ["777","7","77","77"],…

category

4

题型

code_blocks

4

代码语言

hub

3

相关题

当前训练重点

中等 · 数组·哈希·扫描

bolt

答案摘要

遍历数组 `nums`,对于每个 ,枚举所有 ,如果 $i \neq j$ 且 $nums[i] + nums[j] = target$,则答案加一。 时间复杂度 $O(n^2 \times m)$,其中 和 分别为数组 `nums` 和字符串 `target` 的长度。空间复杂度 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

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

解题思路

方法一:枚举

遍历数组 nums,对于每个 ii,枚举所有 jj,如果 iji \neq jnums[i]+nums[j]=targetnums[i] + nums[j] = target,则答案加一。

时间复杂度 O(n2×m)O(n^2 \times m),其中 nnmm 分别为数组 nums 和字符串 target 的长度。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
class Solution:
    def numOfPairs(self, nums: List[str], target: str) -> int:
        n = len(nums)
        return sum(
            i != j and nums[i] + nums[j] == target for i in range(n) for j in range(n)
        )
speed

复杂度分析

指标
时间complexity is O(n * k) where n is the number of strings and k is the average string length, dominated by substring and hash lookups. Space complexity is O(n) for the hash map storing string counts.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Looking for use of hash map to reduce naive O(n^2) pair checks.

  • question_mark

    Interested in handling duplicate strings correctly without overcounting.

  • question_mark

    Expect candidates to separate prefix and suffix logic clearly.

warning

常见陷阱

外企场景
  • error

    Forgetting to exclude self-pairs when prefix equals suffix.

  • error

    Miscounting duplicates by not using frequency map properly.

  • error

    Using nested loops over all pairs which can be slow for larger arrays.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Count pairs for a target concatenation with at most one character difference.

  • arrow_right_alt

    Find pairs of strings whose concatenation is a palindrome.

  • arrow_right_alt

    Return the actual list of index pairs instead of just the count.

help

常见问题

外企场景

连接后等于目标字符串的字符串对题解:数组·哈希·扫描 | LeetCode #2023 中等