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];
}
};
};
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)