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];
        }
    };
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值