[알고리즘] 패턴 마디의 길이


2007. 패턴 마디의 길이


삼성 SW Expert Academy 알고리즘 문제풀기

패턴에서 반복되는 부분을 마디라고 부른다. 문자열을 입력 받아 마디의 길이를 출력하는 프로그램을 작성하라.

[제약 사항]

각 문자열의 길이는 30이다. 마디의 최대 길이는 10이다.

[입력]

가장 첫 줄에는 테스트 케이스의 개수 T가 주어지고, 그 아래로 각 테스트 케이스가 주어진다.

각 테스트 케이스의 첫 번째 줄에는 길이가 30인 문자열이 주어진다.

[출력]

출력의 각 줄은 ‘#t’로 시작하고, 공백을 한 칸 둔 다음 정답을 출력한다.

(t는 테스트 케이스의 번호를 의미하며 1부터 시작한다.)

> 입력
3       
KOREAKOREAKOREAKOREAKOREAKOREA
SAMSUNGSAMSUNGSAMSUNGSAMSUNGSA
GALAXYGALAXYGALAXYGALAXYGALAXY  

> 출력
#1 5
#2 7
#3 6
package lv2;

import java.util.Scanner;

/* 19.08.19
 * SW Expert Academy
 * [2007] 패턴 마디의 길이
 * 반복되는 부분을 마디 -> 마디의 길이를 출력
 */

public class N2007 {
   public static void main(String[] args) {
      Scanner scan = new Scanner(System.in);
      int test = scan.nextInt();
      for (int test_case = 1; test_case <= test; test_case++) { // test case 만큼 Loop
         String str = scan.next();
         for (int i = 1; i <= 10; i++) { // Input data 배열에 삽입
            String pre = str.substring(0, i); // 앞에서 두개 추출
            String next = str.substring(i, i + i);
	    if (pre.equals(next)) {
               System.out.println("#" + test_case + " " + pre.length());
               break;
            }
            if (i == 1) { // 마디가 한 개인 경우 예외처리
               pre = str.substring(0, 1);
               next = str.substring(1, 2);
	       if (pre.equals(next)) {
                  System.out.println("#" + test_case + " " + "1");
                  break;
               }
            }
         }
      }
      scan.close();
   }
}





© 2019. by jun108059

Powered by youngjun