LeetCode 1662: Check If Two String Arrays are Equivalent

ArrayString

Problem Description

Explanation:

To solve this problem, we need to concatenate all strings in each array and compare the resulting strings. If the concatenated strings are the same, the two arrays represent the same string. We can achieve this by iterating through each array, concatenating the strings into two separate strings, and then comparing the two strings.

  • Algorithm:

    1. Initialize two empty strings str1 and str2.
    2. Iterate through each string in word1 and concatenate them to str1.
    3. Iterate through each string in word2 and concatenate them to str2.
    4. Compare str1 and str2. If they are equal, return true; otherwise, return false.
  • Time Complexity: O(n), where n is the total number of characters in both arrays.

  • Space Complexity: O(n), where n is the total number of characters in both arrays.

:

Solutions

class Solution {
    public boolean arrayStringsAreEqual(String[] word1, String[] word2) {
        StringBuilder sb1 = new StringBuilder();
        StringBuilder sb2 = new StringBuilder();
        
        for (String str : word1) {
            sb1.append(str);
        }
        
        for (String str : word2) {
            sb2.append(str);
        }
        
        return sb1.toString().equals(sb2.toString());
    }
}

Loading editor...