
# 문제 출제 사이트
https://www.acmicpc.net/problem/2675
2675번: 문자열 반복
문자열 S를 입력받은 후에, 각 문자를 R번 반복해 새 문자열 P를 만든 후 출력하는 프로그램을 작성하시오. 즉, 첫 번째 문자를 R번 반복하고, 두 번째 문자를 R번 반복하는 식으로 P를 만들면 된다
www.acmicpc.net
# 문제
문자열 S를 입력받은 후에, 각 문자를 R번 반복해 새 문자열 P를 만든 후 출력하는 프로그램을 작성하시오.
즉, 첫 번째 문자를 R번 반복하고, 두 번째 문자를 R번 반복하는 식으로 P를 만들면 된다.
S에는 QR Code "alphanumeric" 문자만 들어있다.
QR Code "alphanumeric" 문자는 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\$%*+-./: 이다.
# 입력
첫째 줄에 테스트 케이스의 개수 T(1 ≤ T ≤ 1,000)가 주어진다.
각 테스트 케이스는 반복 횟수 R(1 ≤ R ≤ 8), 문자열 S가 공백으로 구분되어 주어진다.
S의 길이는 적어도 1이며, 20글자를 넘지 않는다.
# 출력
각 테스트 케이스에 대해 P를 출력한다.
# 제출한 소스코드
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.ArrayList; | |
import java.util.List; | |
import java.util.Scanner; | |
public class Main { | |
public static void main(String[] args) { | |
Scanner sc = new Scanner(System.in); | |
// t => 테스트 케이스의 개수 | |
int t = sc.nextInt(); | |
// resultList 한개의 테스트 케이스가 끝나면 ArrayList에 add한다. | |
List<String> resultList = new ArrayList<>(); | |
// sb => 한개의 테스트 케이스의 글자를 r번 추가(append)하기 위해 사용 | |
StringBuffer sb = new StringBuffer(); | |
for(int i = 0; i < t; i++) { | |
int r = sc.nextInt(); | |
// 문자열 s를 입력할 tempStr 변수 | |
String tempStr = sc.nextLine().trim(); | |
for(int j = 0; j < tempStr.length(); j++) { | |
// tempStr의 j번째 있는 char를 sb에 r번 append해주는 반복문 | |
for(int k = 0; k < r; k++) { | |
sb.append(tempStr.charAt(j)); | |
} | |
} | |
resultList.add(sb.toString()); | |
// sb를 resultList에 add하고 기존에 있는 sb에 문자열을 delete 함수로 삭제 | |
sb.delete(0, sb.length()); | |
} | |
for (String tempStr : resultList) { | |
System.out.println(tempStr); | |
} | |
} | |
} |
- StringBuffer를 delete() 함수를 사용해서 이전 데이터를 메모리에 저장하지 않고 명확하게 "삭제"
-> 인덱스의 값을 기준으로 부문 문자열을 문자열에서 제거
-> 특정 위치의 문자열 중 문자 한 개만을 제거하고 싶을 때는 deleteCharAt() 메소드를 사용
제출한 코드를 좀더 간결하게 작성해봤습니다.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Scanner; | |
public class Main { | |
public static void main(String[] args) { | |
Scanner sc = new Scanner(System.in); | |
int t = sc.nextInt(); | |
StringBuffer sb = new StringBuffer(); | |
for(int i = 0; i < t; i++) { | |
int r = sc.nextInt(); | |
String tempStr = sc.next().trim(); | |
for(int j = 0; j < tempStr.length(); j++) { | |
for(int k = 0; k < r; k++) { | |
sb.append(tempStr.charAt(j)); | |
} | |
} | |
System.out.println(sb); | |
sb.delete(0, sb.length()); | |
} | |
} | |
} |
반응형