Leetcode 1662. Check If Two String Arrays are Equivalent
You are given two string arrays word1
and word2
. A string array represents a sentence by concatenating its elements in order. Return true
if the two sentences represented by the two arrays are the same and false
otherwise.
Input: word1 = ["ab", "c"], word2 = ["a", "bc"]
Output: true
Explanation:
word1 represents "ab" + "c" -> "abc"
word2 represents "a" + "bc" -> "abc"
The strings are the same, so return true.
Input: word1 = ["a", "cb"], word2 = ["ab", "c"]
Output: false
Explanation:
word1 represents "a" + "cb" -> "acb"
word2 represents "ab" + "c" -> "abc"
The strings are not the same, so return false.
Input: word1 = ["abc", "d", "defg"], word2 = ["abcddefg"]
Output: true
Explanation:
word1 represents "abc" + "d" + "defg" -> "abcddefg"
word2 represents "abcddefg" -> "abcddefg"
The strings are the same, so return 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]
and word2[i]
consist of lowercase letters.word1
and word2
are empty?
true
would make sense because empty strings are equal.word1
to form a single string.word2
to form a single string.#include<vector>
#include<string>
#include<iostream>
using namespace std;
bool arrayStringsAreEqual(vector<string>& word1, vector<string>& word2) {
string str1 = "";
string str2 = "";
for (string w : word1)
str1 += w;
for (string w : word2)
str2 += w;
return str1 == str2;
}
// Main function for testing
int main() {
vector<string> word1 = {"ab", "c"};
vector<string> word2 = {"a", "bc"};
cout << (arrayStringsAreEqual(word1, word2) ? "true" : "false") << endl; // true
word1 = {"a", "cb"};
word2 = {"ab", "c"};
cout << (arrayStringsAreEqual(word1, word2) ? "true" : "false") << endl; // false
word1 = {"abc", "d", "defg"};
word2 = {"abcddefg"};
cout << (arrayStringsAreEqual(word1, word2) ? "true" : "false") << endl; // true
return 0;
}
The time complexity of this approach is O(N), where N
is the total number of characters in both word1
and word2
. This is because concatenating all the strings involves iterating through every character in both arrays. Comparing the resulting strings also involves iterating through each character, but this is effectively linear.
The space complexity is also O(N) due to the storage required for the concatenated strings.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?