0%

『LeetCode』1662 检查两个字符串数组是否相等

题目

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

给你两个字符串数组 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 <= 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] 由小写字母组成

标签

数组, 字符串


题解

【检查两个字符串数组是否相等】简单一行模拟

模拟

最简单的方法就是拼接然后模拟,一行代码即可。但空间复杂度为 \(O(n)\)

更好一些的方法是用指针滑动判断对比。

1
2
3
4
5
# Code language: Python
# 滑动指针(迭代器)
class Solution:
def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool:
return all(a == b for a, b in zip_longest(chain(*word1), chain(*word2)))
1
2
3
4
5
# Code language: Python
# 拼接
class Solution:
def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool:
return "".join(word1) == "".join(word2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// Code language: Java
class Solution {
public boolean arrayStringsAreEqual(String[] word1, String[] word2) {
int n1 = word1.length, n2 = word2.length, i = 0, j = 0, p = 0, q = 0;
while (i < n1 && j < n2) {
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 == n1 && j == n2 && p == 0 && q == 0;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
// Code language: C++
class Solution {
public:
bool arrayStringsAreEqual(vector<string>& word1, vector<string>& word2) {
int n1 = word1.size(), n2 = word2.size(), i = 0, j = 0, p = 0, q = 0;
while (i < n1 && j < n2) {
if (word1[i][p] != word2[j][q]) return false;
if (++p >= word1[i].size()) ++i, p = 0;
if (++q >= word2[j].size()) ++j, q = 0;
}
return i == n1 && j == n2 && p == 0 && q == 0;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/* Code language: JavaScript */
/**
* @param {string[]} word1
* @param {string[]} word2
* @return {boolean}
*/
var arrayStringsAreEqual = function(word1, word2) {
let n1 = word1.length, n2 = word2.length, i = 0, j = 0, p = 0, q = 0;
while (i < n1 && j < n2) {
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 == n1 && j == n2 && p == 0 && q == 0;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/* Code language: Go */
func arrayStringsAreEqual(word1 []string, word2 []string) bool {
n1, n2 := len(word1), len(word2)
i, j, p, q := 0, 0, 0, 0
for i < n1 && j < n2 {
if word1[i][p] != word2[j][q] {
return false
}
if p++; p >= len(word1[i]) {
i++; p = 0;
}
if q++; q >= len(word2[j]) {
j++; q = 0;
}
}
return i == n1 && j == n2 && p == 0 && q == 0
}
  • 时间复杂度: \(O(n)\)
  • 空间复杂度: \(O(1)\)

如果对你有帮助的话,请给我点个赞吧~

欢迎前往 我的博客Algorithm - Github 查看更多题解

--- ♥ end ♥ ---

欢迎关注我呀~