leetcode笔记之[1662. 检查两个字符串数组是否相等 ]

141 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第18天,点击查看活动详情

一、题目描述:

1662. 检查两个字符串数组是否相等 - 力扣(LeetCode)

给你两个字符串数组 word1word2 。如果两个数组表示的字符串相同,返回 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

示例 3:

输入:word1  = ["abc", "d", "defg"], word2 = ["abcddefg"]
输出:true

提示:

  • 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] 由小写字母组成

二、思路分析:

方法1

暴力的方法,用append方法把两个数组内的元素各自拼接成两个字符串,然后用equals方法直接比较。

  1. 说一下stringbuffer和stringbuilder的区别,这道题中两个都可以,但是stringbuilder速度更快一些,而stringbuffer是线程安全的,可以同步访问。多数情况下使用stringbuilder,如果要求线程安全则使用stringbuffer。
  2. 从这道题的题解中还学到一点就是数组内的元素同样可以+,eg:s+=word1;而这里加号的意义就是 把数组内的元素拼接在一起。
  3. 最后一点,tostring方法,这里sb1.tostring()返回sb1值的string对象。

方法2

两超长字符串被分割为两字符串数组,则原本的Index可表示为基址+偏移

基址即当前单词在字符串数组中的位置,偏移即当前字母在当前单词中的位置

通过对Index进行约束,逐个判别字符是否相同

三、AC 代码:

class Solution {
    public boolean arrayStringsAreEqual(String[] word1, String[] word2) {
        int index1 = 0;
        int index2 = 0;
        int count1 = 0;
        int count2 = 0;
        while(index1<word1.length && index2<word2.length)
        {
            if(word1[index1].charAt(count1)!=word2[index2].charAt(count2))
            {
                return false;
            }
            count1++;
            count2++;
            if(count1==word1[index1].length())
            {
                index1++;
                count1=0;
            }
            if(count2==word2[index2].length())
            {
                index2++;
                count2=0;
            }
        }
        if(index1!=word1.length || index2!=word2.length)
        {
            return false;
        }
        return true;
    }
}