https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AZPOBiaqNo8DFAWB
SW Expert Academy
SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!
swexpertacademy.com
코딩에 앞서 java 초보인 만큼 코드를 작성하면서 고려한 사항과 적용한 함수에 대해서 작성합니다.
java는 다른 언어들에 비해서 문자열과 정수를 입력받는데 개념을 확실히 해야된는 것 같다.
1. 문자열 입력
- next(): 공백을 기준으로 단어 하나만 입력받음.
- nextLine(): 한 줄을 통째로 입력받음. 공백 포함.
주의사항
- next()와 nextLine()을 함께 사용할 때, 예상치 못한 동작을 할 수 있음. nextInt()나 next()가 실행된 후에는 남은 개행 문자(\n)가 nextLine()에 의해 읽히게 됨. 이로 인해 nextLine()이 의도한 대로 작동하지 않기도 함.
- 해결 방법: nextInt()나 next() 뒤에 nextLine()을 넣거나, Integer.parseInt(sc.nextLine())로 처리.
2. 문자열에서 문자 하나씩 가져오기
- charAt(): 문자열에서 특정 인덱스의 문자 가져옴.
String str = "Hello";
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
System.out.println(ch);
}
3. 문자열 자르기
- split(): 구분자로 문자열을 나눔.
String str = "Hello World"; String[] arr = str.split(" ");
- substring(): 특정 범위의 문자열을 자름.
String str = "Hello World"; String part = str.substring(0, 5); // "Hello"
알고리즘
- 테스트 케이스 수를 입력받는다.
- 각 테스트 케이스마다 문자열과 연산 횟수를 입력받는다.
- 연산 값들을 합산해 전체 회전 횟수를 구한다.
- 회전 횟수를 문자열 길이로 나눈 나머지만큼만 실제로 회전시킬 수 있다.
- 음수 회전 값을 양수로 변환한다.
- 문자열을 회전시켜 결과를 출력한다.
최종코드
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int t = Integer.parseInt(scanner.nextLine());
for (int i = 0; i < t; i++) {
String s = scanner.nextLine();
int k = Integer.parseInt(scanner.nextLine());
long totalRotation = 0;
String[] operations = scanner.nextLine().split(" ");
for (String operation : operations) {
totalRotation += Long.parseLong(operation);
}
totalRotation %= s.length();
if (totalRotation < 0) {
totalRotation += s.length();
}
s = s.substring((int) totalRotation) + s.substring(0, (int) totalRotation);
System.out.println(s);
}
scanner.close();
}
}
'코딩테스트 연습' 카테고리의 다른 글
SW Expert Academy - 2001. 파리 퇴치 D2 (0) | 2025.01.10 |
---|---|
SW Expert Academy - 1204. 최빈수 구하기 D2 (0) | 2025.01.09 |
프로그래머스 주사위 게임3 (1) | 2024.11.23 |
프로그래머스 주식가격 (5) | 2024.10.18 |
프로그래머스 프로 (1) | 2024.10.18 |