LeetCode 1662. 检查两个字符串数组是否相等

给你两个字符串数组 word1 和 word2 。如果两个数组表示的字符串相同,返回 true ;否则,返回 false 。

数组表示的字符串 是由数组中的所有元素 按顺序 连接形成的字符串。

法一:直接拼接字符串之后比较。

法二:不拼接,直接比较,比法一省空间:

class Solution {
public:
    bool arrayStringsAreEqual(vector<string>& word1, vector<string>& word2) {
        int word1OuterIndex = 0;
        int word2OuterIndex = 0;
        int word1InnerIndex = 0;
        int word2InnerIndex = 0;

        while (word1OuterIndex < word1.size() && word2OuterIndex < word2.size()) {
            if (word1InnerIndex == word1[word1OuterIndex].size()) {
                ++word1OuterIndex;
                word1InnerIndex = 0;
                continue;
            }
            if (word2InnerIndex == word2[word2OuterIndex].size()) {
                ++word2OuterIndex;
                word2InnerIndex = 0;
                continue;
            }

            if (word1[word1OuterIndex][word1InnerIndex] != word2[word2OuterIndex][word2InnerIndex]) {
                return false;
            } 

            ++word1InnerIndex;
            ++word2InnerIndex;
        }
        // 由于最后先判断的是word1并对其操作后直接跳出循环,因此以上循环后word2的外层索引应指向其中最后一个字符串,内层索引指向尾后字符时才说明两者的字符数量一致
        return word1OuterIndex == word1.size() && word2OuterIndex == word2.size() - 1 
            && word1InnerIndex == 0 && word2InnerIndex == word2[word2OuterIndex].size();
    }
};

法三:构造一个迭代器使两个输入参数处理起来像一个字符串:

class Solution {
public:
    bool arrayStringsAreEqual(vector<string>& word1, vector<string>& word2) {
        iter it1 = word1;
        iter it2 = word2;

        while (!it1.isEnd() && !it2.isEnd()) {
            if (it1 == it2) {
                ++it1;
                ++it2;
            } else {
                return false;
            }
        }

        return it1.isEnd() && it2.isEnd();
    }
private:
    struct iter {
        vector<string> &data;
        int wordIndex;
        int charIndex;

        iter() = delete;

        iter(vector<string> &vs) : data(vs), wordIndex(0), charIndex(0) { }
        
        iter &operator++() {
            if (++charIndex == data[wordIndex].size()) {
                ++wordIndex;
                charIndex = 0;
                
                if (wordIndex == data.size()) {
                    wordIndex = -1;
                }
            }

            return *this;
        }

        bool isEnd() {
            return this->wordIndex < 0;
        }

        bool operator==(const iter &it) {
            return data[wordIndex][charIndex] == it.data[it.wordIndex][it.charIndex];
        }
    };
};
posted @   epiphanyy  阅读(12)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
点击右上角即可分享
微信分享提示