20221101 - 1662. Check If Two String Arrays are Equivalent 检查两个字符串数组是否相等(遍历)

78 阅读1分钟

Given two string arrays word1 and word2, return true if the two arrays represent the same string, and false otherwise.

A string is represented by an array if the array elements concatenated in order forms the string.

Example 1

Input: word1 = ["ab", "c"], word2 = ["a", "bc"]
Output: true
Explanation:
word1 represents string "ab" + "c" -> "abc"
word2 represents string "a" + "bc" -> "abc"
The strings are the same, so return true.

Example 2

Input: word1 = ["a", "cb"], word2 = ["ab", "c"]
Output: false

Example 3

Input: word1  = ["abc", "d", "defg"], word2 = ["abcddefg"]
Output: true

 

Constraints

  • 1 <= word1.length, word2.length <= 1000
  • 1 <= word1[i].length, word2[i].length <= 1000
  • 1 <= sum(word1[i].length), sum(word2[i].length) <= 1000
  • word1[i] and word2[i] consist of lowercase letters.

Solution

遍历字符串,分别记录两字符串的行和列进行比对。最后要保证两个字符串数组都是遍历完了才是全部对上,注意最后多余的情况。

class Solution {
public:
    bool arrayStringsAreEqual(vector<string>& word1, vector<string>& word2) {
        int i, j, p1, p2;
        i = j = p1 = p2 = 0;
        while (i < word1.size() && j < word2.size()) {
            if (word1[i][p1] != word2[j][p2])
                return false;
            p1++;
            if (p1 == word1[i].size()) {
                i++;
                p1 = 0;
            }
            p2++;
            if (p2 == word2[j].size()) {
                j++;
                p2 = 0;
            }
        }
        return i == word1.size() && j == word2.size();
    }
};

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