LeetCode 题解工作台

检查两个字符串数组是否相等

给你两个字符串数组 word1 和 word2 。如果两个数组表示的字符串相同,返回 true ;否则,返回 false 。 数组表示的字符串 是由数组中的所有元素 按顺序 连接形成的字符串。 示例 1: 输入: word1 = ["ab", "c"], word2 = ["a", "bc"] 输出…

category

2

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·string

bolt

答案摘要

将两个数组中的字符串拼接成两个字符串,然后比较两个字符串是否相等。 时间复杂度 ,空间复杂度 。其中 为数组中字符串的总长度。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·string 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你两个字符串数组 word1word2 。如果两个数组表示的字符串相同,返回 true ;否则,返回 false

数组表示的字符串 是由数组中的所有元素 按顺序 连接形成的字符串。

 

示例 1:

输入:word1 = ["ab", "c"], word2 = ["a", "bc"]
输出:true
解释:
word1 表示的字符串为 "ab" + "c" -> "abc"
word2 表示的字符串为 "a" + "bc" -> "abc"
两个字符串相同,返回 true

示例 2:

输入:word1 = ["a", "cb"], word2 = ["ab", "c"]
输出:false

示例 3:

输入:word1  = ["abc", "d", "defg"], word2 = ["abcddefg"]
输出:true

 

提示:

  • 1 <= word1.length, word2.length <= 103
  • 1 <= word1[i].length, word2[i].length <= 103
  • 1 <= sum(word1[i].length), sum(word2[i].length) <= 103
  • word1[i]word2[i] 由小写字母组成
lightbulb

解题思路

方法一:字符串拼接

将两个数组中的字符串拼接成两个字符串,然后比较两个字符串是否相等。

时间复杂度 O(m)O(m),空间复杂度 O(m)O(m)。其中 mm 为数组中字符串的总长度。

1
2
3
4
class Solution:
    def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool:
        return ''.join(word1) == ''.join(word2)
speed

复杂度分析

指标
时间complexity is (\mathcal{O}(N)) where N is the total number of characters across both arrays, because every character must be examined. Space complexity is (\mathcal{O}(N)) if concatenating the arrays fully, or (\mathcal{O}(1)) with the two-pointer approach.
空间\mathcal{O}(N)
psychology

面试官常问的追问

外企场景
  • question_mark

    Ask about handling arrays of different lengths and empty strings.

  • question_mark

    Probe whether the candidate can optimize space using streaming comparison.

  • question_mark

    Check understanding of subtle off-by-one errors when joining array elements.

warning

常见陷阱

外企场景
  • error

    Assuming arrays of equal length guarantee equivalent strings.

  • error

    Neglecting to preserve the order of elements when concatenating.

  • error

    Using inefficient nested loops instead of direct concatenation or pointer traversal.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Check equivalence ignoring case sensitivity.

  • arrow_right_alt

    Verify equivalence allowing wildcard characters in one array.

  • arrow_right_alt

    Compare arrays where elements may be reversed before concatenation.

help

常见问题

外企场景

检查两个字符串数组是否相等题解:数组·string | LeetCode #1662 简单