From 84f8bc85553245d494e0162331558076ad0de436 Mon Sep 17 00:00:00 2001 From: ashmichheda Date: Sat, 5 Nov 2022 18:50:22 -0700 Subject: [PATCH] add fix for 1768 --- .../java/com/fishercoder/solutions/_1768.java | 18 ++++++++++++ src/test/java/com/fishercoder/_1768Test.java | 29 +++++++++++++++++++ 2 files changed, 47 insertions(+) create mode 100644 src/test/java/com/fishercoder/_1768Test.java diff --git a/src/main/java/com/fishercoder/solutions/_1768.java b/src/main/java/com/fishercoder/solutions/_1768.java index 3881e684eb..72b5995bf1 100644 --- a/src/main/java/com/fishercoder/solutions/_1768.java +++ b/src/main/java/com/fishercoder/solutions/_1768.java @@ -19,4 +19,22 @@ public String mergeAlternately(String word1, String word2) { return sb.toString(); } } + public static class Solution2 { + public String mergeAlternately(String word1, String word2) { + int len1 = word1.length(); + int len2 = word2.length(); + StringBuilder sb = new StringBuilder(); + + int diffLen = Math.min(len1, len2); + int i = 0; + for(i = 0; i < diffLen; i++) { + sb.append(word1.charAt(i)); + sb.append(word2.charAt(i)); + } + if (i >= len1) sb.append(word2.substring(i)); + else sb.append(word1.substring(i)); + + return sb.toString(); + } + } } diff --git a/src/test/java/com/fishercoder/_1768Test.java b/src/test/java/com/fishercoder/_1768Test.java new file mode 100644 index 0000000000..430a9f1967 --- /dev/null +++ b/src/test/java/com/fishercoder/_1768Test.java @@ -0,0 +1,29 @@ +package com.fishercoder; + +import com.fishercoder.solutions._1768; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + + +public class _1768Test { + private static _1768.Solution2 solution2; + private static String word1; + private static String word2; + private static String expected; + private static String actual; + + @BeforeClass + public static void setup() { + solution2 = new _1768.Solution2(); + } + + @Test + public void test1() { + word1 = "abc"; + word2 = "pqr"; + expected = "apbqcr"; + actual = solution2.mergeAlternately(word1, word2); + Assert.assertEquals(actual, expected); + } +}