S E P H ' S

[JAVA] SWEA 15758. 무한 문자열 D3 본문

Algorithm/SWEA

[JAVA] SWEA 15758. 무한 문자열 D3

yoseph0310 2022. 12. 12. 20:30

 

 

SW Expert Academy

SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!

swexpertacademy.com

 

문제풀이

 

처음에는 단순히 입력으로 주어진 문자를 서로의 길이 만큼 반복해서 더한 뒤 대조를 하면 될줄 알았는데 그렇게 하니 메모리초과가 되며 런타임 에러가 발생했다. 그래서 문자열 반복해서 더해서 StringBuilder에 append하여 대조를 했더니 모든 테스트케이스를 통과할 수 있었다.

 

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Solution {
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        int T = Integer.parseInt(br.readLine());
        for (int t = 1; t <= T; t++) {
            StringBuilder sb_S = new StringBuilder();
            StringBuilder sb_T = new StringBuilder();
            String input = br.readLine();
            String[] input_arr = input.split(" ");
            String str_S = input_arr[0];
            String str_T = input_arr[1];

            int S_len = str_S.length();
            int T_len = str_T.length();

            for (int i = 0; i < S_len; i++) {
                sb_T.append(str_T);
            }
            for (int i = 0; i < T_len; i++) {
                sb_S.append(str_S);
            }

            String sS = sb_S.toString();
            String sT = sb_T.toString();

            if (sS.length() > sT.length()) {
                if (sS.contains(sT)) System.out.println("#" + t + " " + "yes");
                else System.out.println("#" + t + " " + "no");
            } else if (sT.length() > sS.length()){
                if (sT.contains(sS)) System.out.println("#" + t + " " + "yes");
                else System.out.println("#" + t + " " + "no");
            } else {
                if (sT.equals(sS)) System.out.println("#" + t + " " + "yes");
                else System.out.println("#" + t + " " + "no");
            }

        }
    }
}

 

'Algorithm > SWEA' 카테고리의 다른 글

[Java] SWEA 1248 공통조상  (0) 2023.07.22
[Python] 11688. Calkin-Wilf tree 1  (0) 2021.10.16
[Python] 2001 파리퇴치  (0) 2021.10.12