|
| 1 | +package com.concept.scala.leetcodeGeneralProblems |
| 2 | + |
| 3 | +import scala.collection.mutable.ListBuffer |
| 4 | + |
| 5 | +/** |
| 6 | + * 1768. Merge Strings Alternately |
| 7 | + * |
| 8 | + * @see https://leetcode.com/problems/merge-strings-alternately/description/?envType=study-plan-v2&envId=leetcode-75 |
| 9 | + * You are given two strings word1 and word2. Merge the strings by adding letters in alternating order, starting with word1. If a string is longer than the other, append the additional letters onto the end of the merged string. |
| 10 | + * |
| 11 | + * Return the merged string. |
| 12 | + * |
| 13 | + * |
| 14 | + * |
| 15 | + * Example 1: |
| 16 | + * |
| 17 | + * Input: word1 = "abc", word2 = "pqr" |
| 18 | + * Output: "apbqcr" |
| 19 | + * Explanation: The merged string will be merged as so: |
| 20 | + * word1: a b c |
| 21 | + * word2: p q r |
| 22 | + * merged: a p b q c r |
| 23 | + * Example 2: |
| 24 | + * |
| 25 | + * Input: word1 = "ab", word2 = "pqrs" |
| 26 | + * Output: "apbqrs" |
| 27 | + * Explanation: Notice that as word2 is longer, "rs" is appended to the end. |
| 28 | + * word1: a b |
| 29 | + * word2: p q r s |
| 30 | + * merged: a p b q r s |
| 31 | + * Example 3: |
| 32 | + * |
| 33 | + * Input: word1 = "abcd", word2 = "pq" |
| 34 | + * Output: "apbqcd" |
| 35 | + * Explanation: Notice that as word1 is longer, "cd" is appended to the end. |
| 36 | + * word1: a b c d |
| 37 | + * word2: p q |
| 38 | + * merged: a p b q c d |
| 39 | + * |
| 40 | + */ |
| 41 | +object MergeStringAlternately { |
| 42 | + def main(args: Array[String]): Unit = { |
| 43 | + val (word1, word2) = ("abcd", "pq") |
| 44 | + |
| 45 | + println(mergeAlternately(word1, word2)) |
| 46 | + } |
| 47 | + |
| 48 | + def mergeAlternately(word1: String, word2: String): String = { |
| 49 | + val (l1, l2) = (word1.length, word2.length) |
| 50 | + val mergedString = word1.zip(word2).map(x => x._1.toString + x._2.toString).mkString |
| 51 | + if (l1 == l2) mergedString |
| 52 | + else { |
| 53 | + val leftoverString = (l1, l2) match { |
| 54 | + case (a, b) if a > b => word1.substring(b) |
| 55 | + case (a, b) if a < b => word2.substring(a) |
| 56 | + case _ => "" |
| 57 | + } |
| 58 | + mergedString + leftoverString |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + |
| 63 | +} |
0 commit comments