Re: [閒聊] 每日LeetCode已回收
1768. Merge Strings Alternately
給你兩個字串s1和s2,合併兩個字串並使其交錯。
Example:
Input: word1 = "abc", word2 = "pqr"
Output: "apbqcr"
Explanation: The merged string will be merged as so:
word1: a b c
word2: p q r
merged: a p b q c r
Example 2:
Input: word1 = "ab", word2 = "pqrs"
Output: "apbqrs"
Explanation: Notice that as word2 is longer, "rs" is appended to the end.
word1: a b
word2: p q r s
merged: a p b q r s
思路:
1.把兩個字串按照順序一個一個放到陣列,直到兩個都放完為止。
Java Code:
----------------------------------------------
class Solution {
public String mergeAlternately(String s1, String s2) {
int n = s1.length();
int m = s2.length();
char[] res = new char[n + m];
int i = 0, j = 0, k = 0;
while (i < n || j < m) {
if (i < n) {
res[k++] = s1.charAt(i++);
}
if (j < m) {
res[k++] = s2.charAt(j++);
}
}
return new String(res);
}
}
----------------------------------------------
--
https://i.imgur.com/bFRiqA3.jpg

--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 122.100.75.86 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1681824299.A.C00.html
→
04/18 21:26,
2年前
, 1F
04/18 21:26, 1F
推
04/18 21:29,
2年前
, 2F
04/18 21:29, 2F
討論串 (同標題文章)
完整討論串 (本文為第 297 之 719 篇):