给两个list,list元素是一些str,比较两列list各自合成一列string之后是不是完全一样(一开始没仔细看题,原来这么简单,考虑太多还WA一次)
思路一:两个游标,分别扫两个list,中途遇到不一样的字符就return False
1 #1662
2 #Runtime: 52 ms
3 #Memory Usage: 13.7 MB
4
5 class Solution(object):
6 def arrayStringsAreEqual(self, word1, word2):
7 """
8 :type word1: List[str]
9 :type word2: List[str]
10 :rtype: bool
11 """
12 p1 = 0
13 p2 = 0
14 pi2 = 0
15 pi1 = 0
16 while p1 < len(word1) and p2 < len(word2):
17 if pi2 < len(word2[p2]) and pi1 < len(word1[p1]) and word1[p1][pi1] != word2[p2][pi2]:
18 return False
19 pi2 += 1
20 if pi2 == len(word2[p2]):
21 p2 += 1
22 pi2 = 0
23 pi1 += 1
24 if pi1 == len(word1[p1]):
25 p1 += 1
26 pi1 = 0
27 if p1 < len(word1) or p2 < len(word2):
28 return False
29 return True
思路二:直接连起来list所有str,直接比较(看Discussion学到的简洁写法)
1 #1662
2 #Runtime: 22 ms
3 #Memory Usage: 13.9 MB
4
5 class Solution(object):
6 def arrayStringsAreEqual(self, word1, word2):
7 """
8 :type word1: List[str]
9 :type word2: List[str]
10 :rtype: bool
11 """
12 return ''.join(word1) == ''.join(word2)