目录
题目
给你两个字符串数组 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
提示:
1 <= word1.length, word2.length <= 103
1 <= word1[i].length, word2[i].length <= 103
1 <= sum(word1[i].length), sum(word2[i].length) <= 103
word1[i] 和 word2[i] 由小写字母组成
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/check-if-two-string-arrays-are-equivalent
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题解
法一:拼接+比较
class Solution:
def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool:
w1=''
w2=''
for i in word1:
w1+=i
for i in word2:
w2+=i
if len(w1)!=len(w2):
return False
else:
for i in range(len(w1)):
if w1[i]!=w2[i]:
return False
return True
比较两个字符串是否相同可直接用 w1==w2判断
class Solution:
def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool:
w1=''
w2=''
for i in word1:
w1+=i
for i in word2:
w2+=i
if w1!=w2:
return False
else:
return True
可利用join()函数拼接字符串,''.joi(w)
''里放用来分隔符
class Solution:
def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool:
return ''.join(word1) == ''.join(word2)
法二:直接遍历
class Solution:
def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool:
i,j=0,0
p1,p2=0,0
while p1<len(word1) and p2<len(word2):
if word1[p1][i]!=word2[p2][j]:
return False
i+=1
if i==len(word1[p1]):
p1+=1
i=0
j+=1
if j==len(word2[p2]):
p2+=1
j=0
return p1 == len(word1) and p2 == len(word2)
注意:最后的return里不能直接写True,这会使得两个字符串的长度不一被判断为True,应该用放在while那的条件再判断一次