文章目录
题目
标题和出处
标题:检查两个字符串数组是否相等
难度
1 级
题目描述
要求
给你两个字符串数组 word1 \texttt{word1} word1 和 word2 \texttt{word2} word2。如果两个数组表示的字符串相同,返回 true \texttt{true} true;否则,返回 false \texttt{false} false。
数组表示的字符串是由数组中的所有元素按顺序连接形成的字符串。
示例
示例 1:
输入:
word1
=
["ab",
"c"],
word2
=
["a",
"bc"]
\texttt{word1 = ["ab", "c"], word2 = ["a", "bc"]}
word1 = ["ab", "c"], word2 = ["a", "bc"]
输出:
true
\texttt{true}
true
解释:
word1
\texttt{word1}
word1 表示的字符串为
"ab"
+
"c"
→
"abc"
\texttt{"ab" + "c"} \rightarrow \texttt{"abc"}
"ab" + "c"→"abc"
word2
\texttt{word2}
word2 表示的字符串为
"a"
+
"bc"
→
"abc"
\texttt{"a" + "bc"} \rightarrow \texttt{"abc"}
"a" + "bc"→"abc"
两个字符串相同,返回
true
\texttt{true}
true
示例 2:
输入:
word1
=
["a",
"cb"],
word2
=
["ab",
"c"]
\texttt{word1 = ["a", "cb"], word2 = ["ab", "c"]}
word1 = ["a", "cb"], word2 = ["ab", "c"]
输出:
false
\texttt{false}
false
示例 3:
输入:
word1
=
["abc",
"d",
"defg"],
word2
=
["abcddefg"]
\texttt{word1 = ["abc", "d", "defg"], word2 = ["abcddefg"]}
word1 = ["abc", "d", "defg"], word2 = ["abcddefg"]
输出:
true
\texttt{true}
true
数据范围
- 1 ≤ word1.length, word2.length ≤ 10 3 \texttt{1} \le \texttt{word1.length, word2.length} \le \texttt{10}^\texttt{3} 1≤word1.length, word2.length≤103
- 1 ≤ word1[i].length, word2[i].length ≤ 10 3 \texttt{1} \le \texttt{word1[i].length, word2[i].length} \le \texttt{10}^\texttt{3} 1≤word1[i].length, word2[i].length≤103
- 1 ≤ sum(word1[i].length), sum(word2[i].length) ≤ 10 3 \texttt{1} \le \texttt{sum(word1[i].length), sum(word2[i].length)} \le \texttt{10}^\texttt{3} 1≤sum(word1[i].length), sum(word2[i].length)≤103
- word1[i] \texttt{word1[i]} word1[i] 和 word2[i] \texttt{word2[i]} word2[i] 由小写字母组成
解法
思路和算法
这道题目要求判断两个数组表示的字符串是否相等。需要对两个数组分别拼接数组中的元素,形成字符串,然后对两个拼接后的字符串比较是否相等。
对于拼接字符串的操作,可以通过 StringBuffer \texttt{StringBuffer} StringBuffer 类型实现。具体做法是,创建两个 StringBuffer \texttt{StringBuffer} StringBuffer 类型的对象,分别用于存储两个字符串数组的元素拼接之后得到的字符串,遍历两个字符串数组,拼接完成之后,判断两个 StringBuffer \texttt{StringBuffer} StringBuffer 类型的对象的字符串内容是否相同。
代码
class Solution {
public boolean arrayStringsAreEqual(String[] word1, String[] word2) {
StringBuffer sb1 = new StringBuffer();
StringBuffer sb2 = new StringBuffer();
int length1 = word1.length, length2 = word2.length;
for (int i = 0; i < length1; i++) {
sb1.append(word1[i]);
}
for (int i = 0; i < length2; i++) {
sb2.append(word2[i]);
}
String str1 = sb1.toString();
String str2 = sb2.toString();
return str1.equals(str2);
}
}
复杂度分析
-
时间复杂度: O ( m + n ) O(m+n) O(m+n),其中 m m m 是字符串数组 word 1 \textit{word}_1 word1 的各元素长度之和, n n n 是 word 2 \textit{word}_2 word2 的各元素长度之和。拼接两个字符串分别需要 O ( m ) O(m) O(m) 和 O ( n ) O(n) O(n) 的时间,判断两个字符串是否相等需要 O ( min ( m , n ) ) O(\min(m,n)) O(min(m,n)) 的时间,因此总时间复杂度是 O ( m + n ) O(m+n) O(m+n)。
-
空间复杂度: O ( m + n ) O(m+n) O(m+n),其中 m m m 是字符串数组 word 1 \textit{word}_1 word1 的各元素长度之和, n n n 是 word 2 \textit{word}_2 word2 的各元素长度之和。拼接后的两个字符串的长度分别是 m m m 和 n n n。