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:
- Initialize two empty strings
str1
andstr2
. - Iterate through each string in
word1
and concatenate them tostr1
. - Iterate through each string in
word2
and concatenate them tostr2
. - Compare
str1
andstr2
. If they are equal, returntrue
; otherwise, returnfalse
.
- Initialize two empty strings
-
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...