-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1768.交替合并字符串.go
98 lines (90 loc) · 1.84 KB
/
1768.交替合并字符串.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/*
* @lc app=leetcode.cn id=1768 lang=golang
*
* [1768] 交替合并字符串
*
* https://leetcode-cn.com/problems/merge-strings-alternately/description/
*
* algorithms
* Easy (75.86%)
* Likes: 22
* Dislikes: 0
* Total Accepted: 16.9K
* Total Submissions: 22.2K
* Testcase Example: '"abc"\n"pqr"'
*
* 给你两个字符串 word1 和 word2 。请你从 word1
* 开始,通过交替添加字母来合并字符串。如果一个字符串比另一个字符串长,就将多出来的字母追加到合并后字符串的末尾。
*
* 返回 合并后的字符串 。
*
*
*
* 示例 1:
*
*
* 输入:word1 = "abc", word2 = "pqr"
* 输出:"apbqcr"
* 解释:字符串合并情况如下所示:
* word1: a b c
* word2: p q r
* 合并后: a p b q c r
*
*
* 示例 2:
*
*
* 输入:word1 = "ab", word2 = "pqrs"
* 输出:"apbqrs"
* 解释:注意,word2 比 word1 长,"rs" 需要追加到合并后字符串的末尾。
* word1: a b
* word2: p q r s
* 合并后: a p b q r s
*
*
* 示例 3:
*
*
* 输入:word1 = "abcd", word2 = "pq"
* 输出:"apbqcd"
* 解释:注意,word1 比 word2 长,"cd" 需要追加到合并后字符串的末尾。
* word1: a b c d
* word2: p q
* 合并后: a p b q c d
*
*
*
*
* 提示:
*
*
* 1
* word1 和 word2 由小写英文字母组成
*
*
*/
// @lc code=start
func mergeAlternately(word1 string, word2 string) string {
ans := []byte{}
l1 := len(word1)
l2 := len(word2)
i, i1, i2 := 0, 0, 0
for i1 < l1 && i2 < l2 {
if i%2 == 0 {
ans = append(ans, word1[i1])
i1++
} else {
ans = append(ans, word2[i2])
i2++
}
i++
}
if i1 < l1 {
ans = append(ans, []byte(word1)[i1:]...)
}
if i2 < l2 {
ans = append(ans, []byte(word2)[i2:]...)
}
return string(ans)
}
// @lc code=end