[Programmers] #181942 - 문자열 섞기 [Java][C++][Python]
길이가 같은 두 문자열의 문자를 번갈아 섞어 하나의 문자열로 만드는 문제.
[Programmers] #181942 - 문자열 섞기 [Java][C++][Python]
1. 아이디어
str1과 str2는 길이가 같으므로, 인덱스를 0부터 하나씩 늘려가며 두 문자열에서 같은 위치의 문자를 번갈아 결과 문자열에 이어 붙이면 된다.
2. 복잡도
| 접근 | 시간 | 공간 |
|---|---|---|
| 풀이 | $O(N)$ | $O(N)$ |
($N$ = str1(=str2)의 길이)
3. 코드
풀이 [Java][C++][Python]
1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public String solution(String str1, String str2) {
StringBuilder sb = new StringBuilder();
int idx = 0;
while (idx < str1.length()) {
sb.append(str1.charAt(idx)).append(str2.charAt(idx));
idx++;
}
return sb.toString();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <bits/stdc++.h>
using namespace std;
string solution(string str1, string str2) {
string s;
int idx = 0;
while (idx < str1.size()) {
s += str1[idx];
s += str2[idx];
idx++;
}
return s;
}
1
2
def solution(str1, str2):
return "".join(a + b for a, b in zip(str1, str2))
This post is licensed under CC BY 4.0 by the author.