跳至主要內容

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


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

🟢   🔖  数组 字符串  🔗 力扣open in new window LeetCodeopen in new window

题目

Given two string arrays word1 and word2, return true if the two arrays represent the same string, and false otherwise.

A string is represented by an array if the array elements concatenated in order forms the string.

Example 1:

Input: word1 = ["ab", "c"], word2 = ["a", "bc"]

Output: true

Explanation:

word1 represents string "ab" + "c" -> "abc"

word2 represents string "a" + "bc" -> "abc"

The strings are the same, so return true.

Example 2:

Input: word1 = ["a", "cb"], word2 = ["ab", "c"]

Output: false

Example 3:

Input: word1 = ["abc", "d", "defg"], word2 = ["abcddefg"]

Output: true

Constraints:

  • 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] and word2[i] consist of lowercase letters.

题目大意

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

解题思路

题目要求判断两个字符串数组是否在连接后形成相同的字符串,通过直接将两个数组分别连接成字符串,然后比较是否相等即可。

  1. 连接字符串
    • 使用 Array.prototype.join('') 方法将数组中的所有字符串拼接为一个完整的字符串。
  2. 比较字符串
    • 使用 ===== 直接比较两个拼接后的字符串。

复杂度分析

  • 时间复杂度O(m + n),其中 mn分别为 word1word2 的总字符数。
    • join('') 操作需要遍历整个数组,时间复杂度为 O(m + n)
    • 字符串比较的时间复杂度为 O(min(m, n))
    • 整体复杂度为 O(m + n)
  • 空间复杂度O(m + n),需要额外的空间存储连接后的两个字符串。

代码

/**
 * @param {string[]} word1
 * @param {string[]} word2
 * @return {boolean}
 */
var arrayStringsAreEqual = function (word1, word2) {
	return word1.join('') === word2.join('');
};

相关题目

题号标题题解标签难度力扣
2060同源字符串检测字符串 动态规划🔴🀄️open in new window 🔗open in new window