[BaekJoon] #2675 - 문자열 반복 [Java][C++][Python]
[BaekJoon] #2675 - 문자열 반복 [Java][C++][Python]
1. 아이디어
문자열 $S$의 각 문자를 앞에서부터 $R$번씩 이어 붙이는 문제로, 문자열 전체가 아니라 문자 단위로 반복한다.
2. 코드
풀이 [Java][C++][Python]
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
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
int t = Integer.parseInt(br.readLine());
while (t-- > 0) {
StringTokenizer st = new StringTokenizer(br.readLine());
int r = Integer.parseInt(st.nextToken());
String s = st.nextToken();
for (char c : s.toCharArray()) {
for (int i = 0; i < r; i++) {
sb.append(c);
}
}
sb.append("\n");
}
System.out.println(sb);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int t;
cin >> t;
while (t--) {
int r;
string s;
cin >> r >> s;
for (char c : s) {
cout << string(r, c);
}
cout << '\n';
}
}
std::string(r, c)는 문자 c를 r개 채운 문자열이라 문자를 반복해 출력하는 데 썼다.
1
2
3
4
5
6
7
8
import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
r, s = input().split()
print("".join(c * int(r) for c in s))
문자열에 정수를 곱하면 그 횟수만큼 반복되므로 c * int(r)로 문자를 반복했다.
This post is licensed under CC BY 4.0 by the author.