Problem Description

gives you two string arrays word1 and word2. Returns true if the strings represented by the two arrays are the same; otherwise, returns false.

A string represented by an array is a string formed by concatenating all the elements in the array in order.

Example 1:

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

Example 2:

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

Example 3:

 输入:word1  = ["abc", "d", "defg"], word2 = ["abcddefg"]
输出:true
Likou original title address: https://leetcode.cn/problems/check-if-two-string-arrays-are-equivalent

solution

The idea is very simple, just convert the array into a string, and then do a comparison to see if they are equal.

Array to string has the following schemes:

  1. toString() method
  2. String() method
  3. join() method
  4. Array loop string concatenation

This question uses methods 3 and 4

Scheme 1 join() method

 var arrayStringsAreEqual = function (word1, word2) {
    let str1 = word1.join('')
    let str2 = word2.join('')
    return str1 === str2
};

Scheme two array loop string concatenation

 var arrayStringsAreEqual = function (word1, word2) {
    let str1 = ''
    word1.forEach((item) => {
        str1 = str1 + item
    })
    let str2 = ''
    word2.forEach((item) => {
        str2 = str2 + item
    })
    return str1 === str2
};

水冗水孚
1.1k 声望585 粉丝

每一个不曾起舞的日子,都是对生命的辜负