Skip to content

Latest commit

 

History

History
39 lines (33 loc) · 938 Bytes

1768.交替合并字符串.md

File metadata and controls

39 lines (33 loc) · 938 Bytes

1768.交替合并字符串

/*
 * @lc app=leetcode.cn id=1768 lang=typescript
 *
 * [1768] 交替合并字符串
 */

// @lc code=start
function mergeAlternately(word1: string, word2: string): string {}
// @lc code=end

解法 1: 双指针枚举

function mergeAlternately(word1: string, word2: string): string {
  let i = 0,
    j = 0,
    res = ''
  while (i < word1.length && j < word2.length) res += word1[i++] + word2[j++]
  while (i < word1.length) res += word1[i++]
  while (j < word2.length) res += word2[j++]
  return res
}

Case

test.each([
  { input: { word1: 'abc', word2: 'pqr' }, output: 'apbqcr' },
  { input: { word1: 'ab', word2: 'pqrs' }, output: 'apbqrs' },
  { input: { word1: 'abcd', word2: 'pq' }, output: 'apbqcd' },
])('input: word1 = $input.word1, word2 = $input.word2', ({ input: { word1, word2 }, output }) => {
  expect(mergeAlternately(word1, word2)).toEqual(output)
})