1. Given two string arrays word1 and word2, return true if the two arrays represent the same string, and false otherwise.
  2. A string is represented by an array if the array elements concatenated in order forms the string.
  3. Example 1:
  4. Input: word1 = ["ab", "c"], word2 = ["a", "bc"]
  5. Output: true
  6. Explanation:
  7. word1 represents string "ab" + "c" -> "abc"
  8. word2 represents string "a" + "bc" -> "abc"
  9. The strings are the same, so return true.
  10. Example 2:
  11. Input: word1 = ["a", "cb"], word2 = ["ab", "c"]
  12. Output: false
  13. Example 3:
  14. Input: word1 = ["abc", "d", "defg"], word2 = ["abcddefg"]
  15. Output: true
  16. Constraints:
  17. 1 <= word1.length, word2.length <= 103
  18. 1 <= word1[i].length, word2[i].length <= 103
  19. 1 <= sum(word1[i].length), sum(word2[i].length) <= 103
  20. word1[i] and word2[i] consist of lowercase letters.

这题最简单的做法就是把字符串进行拼接然后比较。我这里用索引来计算,但是实际时间复杂度好像没差什么。

  1. class CheckIfTwoStringArraysAreEquivalent : public Solution {
  2. public:
  3. void Exec() {
  4. }
  5. bool arrayStringsAreEqual(vector<string>& word1, vector<string>& word2) {
  6. int word2i = 0, word2j = 0;
  7. for (int i = 0; i < word1.size(); i++) {
  8. for (int j = 0; j < word1[i].size(); j++) {
  9. if (word2i >= word2.size()) {
  10. return false;
  11. }
  12. if (word1[i][j] != word2[word2i][word2j]) {
  13. return false;
  14. }
  15. ++word2j;
  16. if (word2j >= word2[word2i].size()) {
  17. ++word2i; word2j = 0;
  18. }
  19. }
  20. }
  21. if (word2i != word2.size() || 0 != word2j) {
  22. return false;
  23. }
  24. return true;
  25. }
  26. };
共 0 条回复
暂时没有人回复哦,赶紧抢沙发
发表新回复

作者

sryan
today is a good day