检查两个字符串数组是否相等
问题描述:
给你两个字符串数组 word1 和 word2 。如果两个数组表示的字符串相同,返回 true ;否则,返回 false 。
数组表示的字符串 是由数组中的所有元素 按顺序 连接形成的字符串。
示例 1:
输入:word1 = [“ab”, “c”], word2 = [“a”, “bc”]
输出:true
解释:
word1 表示的字符串为 “ab” + “c” -> “abc”
word2 表示的字符串为 “a” + “bc” -> “abc”
两个字符串相同,返回 true
示例 2:
输入:word1 = [“a”, “cb”], word2 = [“ab”, “c”]
输出:false
问题求解:
class Solution:
def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool:
return "".join(word1) == "".join(word2)
问题总结:
老规矩我们先看一下官方求解思路。
方法一:拼接字符串进行对比
思路与算法
将 \textit{word1}word1 和 \textit{word2}word2 按顺序拼接成两个字符串,进行比较即可。
方法二:遍历
思路与算法
更进一步的想法,我们可以直接在 \textit{word1}word1 和 \textit{word2}word2 上进行对比,避免额外创建字符串。
设置两个指针 \textit{p1}p1 和 \textit{p2}p2 分别表示遍历到了 \textit{word1}[\textit{p1}]word1[p1] 和 \textit{word2}[\textit{p2}]word2[p2],另外还需设置两个指针 ii 和 jj,表示正在对比 \textit{word1}[\textit{p1}][i]word1[p1][i] 和 \textit{word2}[\textit{p2}][j]word2[p2][j]。
如果 \textit{word1}[\textit{p1}][i] \neq \textit{word2}[\textit{p2}][j]word1[p1][i]
=word2[p2][j],则直接返回 \textit{false}false。否则 i + 1i+1,当 i = \textit{word1}[\textit{p1}].lengthi=word1[p1].length 时,表示对比到当前字符串末尾,需要将 \textit{p1} + 1p1+1,ii 赋值为 00。jj 和 \textit{p2}p2 同理。
当 \textit{p1} \lt \textit{word1}.lengthp1<word1.length 或者 \textit{p2} \lt \textit{word2}.lengthp2<word2.length 不满足时,算法结束。最终两个数组相等条件即为 \textit{p1} = \textit{word1}.lengthp1=word1.length 并且 \textit{p2} = \textit{word2}.lengthp2=word2.length。
作者:LeetCode-Solution
链接:https://leetcode.cn/problems/check-if-two-string-arrays-are-equivalent/solution/jian-cha-liang-ge-zi-fu-chuan-shu-zu-shi-9iuo/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。