Home [LeetCode] 1768. Merge Strings Alternately (交替合併字符串)
Post
Cancel

[LeetCode] 1768. Merge Strings Alternately (交替合併字符串)

1768.Merge Strings Alternately

1768.Merge Strings Alternately

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.

Return the merged string.

給你兩個字串 word1 和 word2 。請你從 word1 開始,透過交替加上字母來合併字串。如果一個字串比另一個字串長,就將出來多的字母追加到合併後字串的組成。

傳回合併後的字串。

範例1:

1
2
3
4
5
6
輸入:word1 = "abc", word2 = "pqr"
輸出:"apbqcr"
解釋:字串合併情況如下所示:
單字1: a b c
單字2: p q r
合併後: a p b q c r

範例2:

1
2
3
4
5
6
輸入:word1 = "ab", word2 = "pqrs"
輸出:"apbqrs"
解釋:注意,word2比word1長,"rs" 需要追加到合併後字串的補充。
單字1: a b
單字2: p q r s
合併後: a p b q r s

範例3:

1
2
3
4
5
6
輸入:word1 = "abcd", word2 = "pq"
輸出:"apbqcd"
解釋:注意,word1比word2長,"cd" 需要追加到合併後字串的補充。
單字1: a b c d
詞2: p q
合併後: a p b q c d

解題實作

使用StringBuilder來處理可變動的字元字串。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class Solution {
	public string MergeAlternately(string word1, string word2) {
		int minLen = Math.Min(word1.Length, word2.Length); //最小長度
		string s = (word1.Length > word2.Length) ? word1.Substring(minLen): word2.Substring(minLen); //剩餘字串(最後要追加的字串)

		//使用StringBuilder來處理可變動的字元字串
		StringBuilder sb = new StringBuilder();
		for(int i = 0; i < minLen; i++) {
			//從work1開始交替合併字串
			sb.Append(word1[i]).Append(word2[i]);
		}
		//追加最後的字串
		sb.Append(s);

		return sb.ToString();
	}
}

運行結果:时间 80 ms 内存 36.7 MB

TODO: 先求完成,有空再優化,呵呵 ^.^

[MSDN] StringBuilder 類別

This post is licensed under CC BY 4.0 by the author.