We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent d0f7ba7 commit fd318bdCopy full SHA for fd318bd
java/1768-merge-strings-alternately.java
@@ -1,17 +1,23 @@
1
class Solution {
2
public String mergeAlternately(String word1, String word2) {
3
- int i = 0, j = 0;
+ int i = 0;
4
StringBuilder res = new StringBuilder();
5
6
- while (i < word1.length() && j < word2.length()) {
7
- res.append(word1.charAt(i));
8
- res.append(word2.charAt(j));
+ while (i < word1.length() || i < word2.length()) {
+ if (i < word1.length()) {
+ res.append(word1.charAt(i));
9
+ }
10
+ if (i < word2.length()) {
11
+ res.append(word2.charAt(i));
12
13
i++;
- j++;
14
}
15
- res.append(word1.substring(i));
- res.append(word2.substring(j));
16
return res.toString();
17
-}
18
+}
19
+
20
+/**
21
+ * Time Complexity : O(n+m)
22
+ * Space Complexity : O(n+m)
23
+ */
0 commit comments