Skip to content

Commit 823a7a1

Browse files
solves merge strings alternately
1 parent ca71a8a commit 823a7a1

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -431,7 +431,7 @@
431431
| 1752 | [Check if Array Is Sorted and Rotated](https://leetcode.com/problems/check-if-array-is-sorted-and-rotated) | [![Java](assets/java.png)](src/CheckIfArrayIsSortedAndRotated.java) | |
432432
| 1758 | [Minimum Changes To Make Alternating Binary String](https://leetcode.com/problems/minimum-changes-to-make-alternating-binary-string) | [![Java](assets/java.png)](src/MinimumChangesToMakeAlternatingBinaryString.java) | |
433433
| 1763 | [Longest Nice Substring](https://leetcode.com/problems/longest-nice-substring) | [![Java](assets/java.png)](src/LongestNiceSubstring.java) | |
434-
| 1768 | [Merge Strings Alternately](https://leetcode.com/problems/merge-strings-alternately) | | |
434+
| 1768 | [Merge Strings Alternately](https://leetcode.com/problems/merge-strings-alternately) | [![Java](assets/java.png)](src/MergeStringsAlternately.java) | |
435435
| 1773 | [Count Items Matching a Rule](https://leetcode.com/problems/count-items-matching-a-rule) | | |
436436
| 1779 | [Find Nearest Point That Has the Same X or Y Coordinate](https://leetcode.com/problems/find-nearest-point-that-has-the-same-x-or-y-coordinate) | | |
437437
| 1784 | [Check if Binary String Has at Most One Segment of Ones](https://leetcode.com/problems/check-if-binary-string-has-at-most-one-segment-of-ones) | | |

src/MergeStringsAlternately.java

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
public class MergeStringsAlternately {
2+
public String mergeAlternately(String word1, String word2) {
3+
final StringBuilder result = new StringBuilder();
4+
final String[] words = {word1, word2};
5+
int i = 0, maxLen = Math.max(word1.length(), word2.length());
6+
for (int[] indexes = {0, 0} ; indexes[0] < maxLen || indexes[1] < maxLen ; i ^= 1) {
7+
result.append(get(words[i], indexes[i]));
8+
indexes[i]++;
9+
}
10+
return result.toString();
11+
}
12+
13+
private String get(String s, int index) {
14+
if (index < s.length()) return s.charAt(index) + "";
15+
return "";
16+
}
17+
}

0 commit comments

Comments
 (0)