1662. Check If Two String Arrays are Equivalent - Easy
前往題目
想法
- 雙指針,一對一對比較
思路
自己寫出來了,不過應該可以再更簡潔一點,麻煩的就是出界問題而已
- 疊代所有
word
直到有一方或雙方都出界 - 每次都檢查是否為相同字母
- 相同就字母指針往前
- 檢查字母指針是否出界,如果出界就移動
word
指針,並且歸零字母指針
Code
class Solution {
public boolean arrayStringsAreEqual(String[] word1, String[] word2) {
int index1 = 0, index2 = 0; // word指針
int charIndex1 = 0; // 字母指針
int charIndex2 = 0;
// 疊代所有word直到有一方或雙方都出界
while (index1 < word1.length && index2 < word2.length) {
// Check if the same
if (word1[index1].charAt(charIndex1) != word2[index2].charAt(charIndex2))
return false;
// Move char pointers
++charIndex1;
++charIndex2;
// Move word pointers
if (charIndex1 >= word1[index1].length()) {
++index1;
charIndex1 = 0;
}
if (charIndex2 >= word2[index2].length()) {
++index2;
charIndex2 = 0;
}
}
// Check if both have reached the end
return index1 >= word1.length &&
index2 >= word2.length &&
charIndex1 == 0 &&
charIndex2 == 0 ?
true :
false;
}
}
和Neetcode大大的解法相同👍
1662. Check If Two String Arrays are Equivalent - Easy
https://f88083.github.io/2024/07/04/1662-Check-If-Two-String-Arrays-are-Equivalent/