LeetCode 75
Merge Strings Alternately
- Problem
- LC 1768
- Topic
- Array / String
- File
- official75_LC1768MergeStringsAlternately.java
- Path
- pkg5leetcode/official75/official75_LC1768MergeStringsAlternately.java
- Package
- pkg5leetcode.official75
- Command
- java pkg5leetcode/official75/official75_LC1768MergeStringsAlternately.java
- Approach
- Two pointers append from word1 and word2 alternately.
- Complexity
- Time O(m+n), Space O(m+n)
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg5leetcode.official75;2 3/*4 * Merge Strings Alternately | LC 17685 * APPROACH: Two pointers append from word1 and word2 alternately.6 * COMPLEXITY: Time O(m+n), Space O(m+n)7 */8public class official75_LC1768MergeStringsAlternately {9 static String mergeAlternately(String word1, String word2) {10 StringBuilder sb = new StringBuilder();11 int i = 0, j = 0;12 while (i < word1.length() || j < word2.length()) {13 if (i < word1.length()) sb.append(word1.charAt(i++));14 if (j < word2.length()) sb.append(word2.charAt(j++));15 }16 return sb.toString();17 }18 19 public static void main(String[] args) {20 check("apbqcr".equals(mergeAlternately("abc", "pqr")), "case1");21 check("apbqrs".equals(mergeAlternately("ab", "pqrs")), "case2");22 System.out.println("all tests passed");23 }24 25 static void check(boolean cond, String name) {26 if (!cond) throw new AssertionError("FAILED: " + name);27 System.out.println(" PASS " + name);28 }29}