문자열 a, b 를 각각 무한대로 반복한 결과가 같은지 확인하는 문제이다.
a를 b의 길이만큼 반복하고 b를 a의 길이만큼 반복하여 비교하면 무한대로 반복했을 때의 결과가 나오게 되며 이를 비교하면 된다.
for(int i=0; i<b.length(); i++) {
fa.append(a);
}
for(int i=0; i<a.length(); i++) {
fb.append(b);
}
if(fa.toString().equals(fb.toString())) sb.append("yes");
else sb.append("no");
또는, 듀 문자열을 서로 다르게 붙여보는 것이다. a를 앞, b를 뒤, b를 앞, a를 뒤로 붙였을 때 같아야 무한히 반복해도 같기 때문이다.
String abCombine = a + b;
String baCombine = b + a;
if (abCombine.equals(baCombine)) {
sb.append("yes");
} else {
sb.append("no");
}
sb.append('\n');
결과 코드는 다음과 같다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine());
StringBuilder sb = new StringBuilder();
for (int tc = 1; tc <= T; tc++) {
sb.append('#').append(tc).append(' ');
StringTokenizer st = new StringTokenizer(br.readLine());
String a = st.nextToken(), b = st.nextToken();
String abCombine = a + b;
String baCombine = b + a;
// StringBuilder fa = new StringBuilder(), fb = new StringBuilder();
// for(int i=0; i<b.length(); i++) {
// fa.append(a);
// }
// for(int i=0; i<a.length(); i++) {
// fb.append(b);
// }
// if(fa.toString().equals(fb.toString())) sb.append("yes");
// else sb.append("no");
if (abCombine.equals(baCombine)) {
sb.append("yes");
} else {
sb.append("no");
}
sb.append('\n');
}
br.close();
System.out.print(sb);
}
}'알고리즘(백준 등) 공부' 카테고리의 다른 글
| SWEA 15230. 알파벳 공부 (0) | 2026.05.09 |
|---|---|
| SWEA 15612. 체스판 위의 룩 배치 (0) | 2026.05.08 |
| SWEA 15942. 외계인 침공 (0) | 2026.05.06 |
| SWEA 16002. 합성수 방정식 (0) | 2026.05.05 |
| SWEA 16003. 화면 캡쳐 (0) | 2026.05.05 |