使用最直接方法,先将两个单词拼接出来,再进行整体判断:

class Solution {
public:
    bool arrayStringsAreEqual(vector<string>& word1, vector<string>& word2) {
        string s1,s2;
        
        for(auto str:word1)
            s1 += str;
        
        for(auto str:word2)
            s2 += str;
        
        return s1 == s2;
    }
};

运行效率:

Runtime: 4 ms, faster than 89.96% of C++ online submissions for Check If Two String Arrays are Equivalent.
Memory Usage: 11.6 MB, less than 80.61% of C++ online submissions for Check If Two String Arrays are Equivalent.

我们也可以不拼接直接比较,空间复杂度为O(1).

class Solution {
public:
    bool arrayStringsAreEqual(vector<string>& word1, vector<string>& word2) {
        int m1 = 0,m2 = 0;
        int n1 = 0,n2 = 0;
        while(m1 < word1.size() && m2 < word2.size())
        {
            while(word1[m1][n1++] != word2[m2][n2++])
                return false;
            
            if(n1 >= word1[m1].size())
                m1++,n1 = 0;
            
            if(n2 >= word2[m2].size())
                m2++,n2 = 0;
        }
        
        return m1== word1.size() && m2==word2.size();
    }
};

运行效率:

Runtime: 0 ms, faster than 100.00% of C++ online submissions for Check If Two String Arrays are Equivalent.
Memory Usage: 11.2 MB, less than 97.31% of C++ online submissions for Check If Two String Arrays are Equivalent.