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
把两个字符串数组中的字符串拼接,然后判断它们是否相等。
思路:
用StringBuilder拼接,然后判断是否相等即可。
public boolean arrayStringsAreEqual(String[] word1, String[] word2) {
StringBuilder str1 = new StringBuilder();
StringBuilder str2 = new StringBuilder();
int n = Math.max(word1.length, word2.length);
for(int i = 0; i < n; i++) {
if(i < word1.length) str1.append(word1[i]);
if(i < word2.length) str2.append(word2[i]);
}
return str1.toString().equals(str2.toString());
}