LeetCode 题解工作台
检查两个字符串数组是否相等
给你两个字符串数组 word1 和 word2 。如果两个数组表示的字符串相同,返回 true ;否则,返回 false 。 数组表示的字符串 是由数组中的所有元素 按顺序 连接形成的字符串。 示例 1: 输入: word1 = ["ab", "c"], word2 = ["a", "bc"] 输出…
2
题型
7
代码语言
3
相关题
当前训练重点
简单 · 数组·string
答案摘要
将两个数组中的字符串拼接成两个字符串,然后比较两个字符串是否相等。 时间复杂度 ,空间复杂度 。其中 为数组中字符串的总长度。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·string 题型思路
题目描述
给你两个字符串数组 word1 和 word2 。如果两个数组表示的字符串相同,返回 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 <= 1031 <= word1[i].length, word2[i].length <= 1031 <= sum(word1[i].length), sum(word2[i].length) <= 103word1[i]和word2[i]由小写字母组成
解题思路
方法一:字符串拼接
将两个数组中的字符串拼接成两个字符串,然后比较两个字符串是否相等。
时间复杂度 ,空间复杂度 。其中 为数组中字符串的总长度。
class Solution:
def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool:
return ''.join(word1) == ''.join(word2)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | 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) |
面试官常问的追问
外企场景- 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.
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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.