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

题目描述

这是 LeetCode 上的 1662. 检查两个字符串数组是否相等 ,难度为 简单

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

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

示例 1:

1
2
3
4
5
6
7
8
输入:word1 = ["ab", "c"], word2 = ["a", "bc"]

输出:true

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

示例 2:
1
2
3
输入:word1 = ["a", "cb"], word2 = ["ab", "c"]

输出:false

示例 3:
1
2
3
输入:word1  = ["abc", "d", "defg"], word2 = ["abcddefg"]

输出:true

提示:

  • $1 <= word1.length, word2.length <= 10^3$
  • $1 <= word1[i].length, word2[i].length <= 10^3$
  • $1 <= sum(word1[i].length), sum(word2[i].length) <= 10^3$
  • word1[i]word2[i] 由小写字母组成

双指针

word1word2 的长度记为 $n$ 和 $m$。

题目本质是要我们比较两个数组扁平化后的字符串是否相同。

使用变量 ij 代表当前处理到哪个 $word1[i]$ 和 $word2[j]$,使用变量 pq 代表当前比较到 $word1[i]$ 和 $word2[j]$ 的哪一位。

最后根据是否能顺利比较完返回相应答案。

Java 代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public boolean arrayStringsAreEqual(String[] word1, String[] word2) {
int n = word1.length, m = word2.length;
int i = 0, j = 0, p = 0, q = 0;
while (i < n && j < m) {
if (word1[i].charAt(p++) != word2[j].charAt(q++)) return false;
if (p == word1[i].length()) {
i++; p = 0;
}
if (q == word2[j].length()) {
j++; q = 0;
}
}
return i == n && j == m;
}
}

TypeScript 代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
function arrayStringsAreEqual(word1: string[], word2: string[]): boolean {
const n = word1.length, m = word2.length
let i = 0, j = 0, p = 0, q = 0
while (i < n && j < m) {
if (word1[i][p++] != word2[j][q++]) return false
if (p == word1[i].length) {
i++; p = 0
}
if (q == word2[j].length) {
j++; q = 0
}
}
return i == n && j == m
}

Python 代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution:
def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool:
n, m = len(word1), len(word2)
i, j, p, q = 0, 0, 0, 0
while i < n and j < m:
if word1[i][p] != word2[j][q]:
return False
p, q = p + 1, q + 1
if p == len(word1[i]):
i, p = i + 1, 0
if q == len(word2[j]):
j, q = j + 1, 0
return i == n and j == m

  • 时间复杂度:$O(\sum{i = 0}^{n - 1}word1[i].length + \sum{j = 0}^{m - 1}word2[j].length)$
  • 空间复杂度:$O(1)$

最后

这是我们「刷穿 LeetCode」系列文章的第 No.1662 篇,系列开始于 2021/01/01,截止于起始日 LeetCode 上共有 1916 道题目,部分是有锁题,我们将先把所有不带锁的题目刷完。

在这个系列文章里面,除了讲解解题思路以外,还会尽可能给出最为简洁的代码。如果涉及通解还会相应的代码模板。

为了方便各位同学能够电脑上进行调试和提交代码,我建立了相关的仓库:https://github.com/SharingSource/LogicStack-LeetCode

在仓库地址里,你可以看到系列文章的题解链接、系列文章的相应代码、LeetCode 原题链接和其他优选题解。


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!