• 【LeetCode】1662.检查两个字符串数组是否相等


    目录

    题目

    题解

    法一:拼接+比较

     法二:直接遍历


    题目

    给你两个字符串数组 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
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    题解

    法一:拼接+比较

    1. class Solution:
    2. def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool:
    3. w1=''
    4. w2=''
    5. for i in word1:
    6. w1+=i
    7. for i in word2:
    8. w2+=i
    9. if len(w1)!=len(w2):
    10. return False
    11. else:
    12. for i in range(len(w1)):
    13. if w1[i]!=w2[i]:
    14. return False
    15. return True

    比较两个字符串是否相同可直接用 w1==w2判断 

    1. class Solution:
    2. def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool:
    3. w1=''
    4. w2=''
    5. for i in word1:
    6. w1+=i
    7. for i in word2:
    8. w2+=i
    9. if w1!=w2:
    10. return False
    11. else:
    12. return True

     可利用join()函数拼接字符串,''.joi(w)

    ''里放用来分隔符

    1. class Solution:
    2. def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool:
    3. return ''.join(word1) == ''.join(word2)

     法二:直接遍历

    1. class Solution:
    2. def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool:
    3. i,j=0,0
    4. p1,p2=0,0
    5. while p1<len(word1) and p2<len(word2):
    6. if word1[p1][i]!=word2[p2][j]:
    7. return False
    8. i+=1
    9. if i==len(word1[p1]):
    10. p1+=1
    11. i=0
    12. j+=1
    13. if j==len(word2[p2]):
    14. p2+=1
    15. j=0
    16. return p1 == len(word1) and p2 == len(word2)

     注意:最后的return里不能直接写True,这会使得两个字符串的长度不一被判断为True,应该用放在while那的条件再判断一次

     

  • 相关阅读:
    【Netty专题】【网络编程】从OSI、TCP/IP网络模型开始到BIO、NIO(Netty前置知识)
    理解和熟悉递归中的尝试
    抖音广告IOS/Android接入笔记:
    Java后端模拟面试,题集①
    【深度学习】第四章:循环神经网络
    JUC——Semaphore
    【数论】约数
    JAVA获取30天或某段范围日期的方法
    【Redis】基于Redis6的数据类型以及相关命令、应用场景整理
    AcWing 数据结构
  • 原文地址:https://blog.csdn.net/Chen_beichen/article/details/127658852