2007 패턴 마디의 길이

Sungmin·2023년 10월 25일
0

SWEA 알고리즘

목록 보기
4/26

패턴 마디의 길이 URL

내 풀이

import java.io.*;

public class SW2007 {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int T = Integer.parseInt(br.readLine());

        for (int i = 1; i <= T; i++) {
            String s = br.readLine();
            int cnt = 1; //문자열길이
            
            String answer = "";
            answer += s.charAt(0);
            for (int j = 1; j < s.length(); j++) {
                answer += s.charAt(j);
                cnt++;
                if (s.charAt(0) == s.charAt(j)) {
                    if (s.substring(0, cnt-1) == s.substring(cnt-1, cnt+1)) {
                        cnt--;
                        break;
                    }
                }
            }
            System.out.println("#" + i + " " + cnt);
        }
    }
}

Solution

import java.io.*;

public class SW2007 {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int T = Integer.parseInt(br.readLine());

        for (int i = 1; i <= T; i++) {
            String s = br.readLine();
            int cnt = 0; //문자열길이
            for (int j = 1; j < s.length(); j++) {
                if (s.charAt(0) == s.charAt(j)) {
                    if (s.substring(0, j).equals(s.substring(j, j+j))) {
                        cnt = j;
                        break;
                    }
                }
            }
            System.out.println("#" + i + " " + cnt);
        }
    }
}

배운점

이 문제자체가 좀 이상하다.
예외처리가 잘 안된 문제같다
난 예외를 생각해서 KAKAOKAKAOKAKAO...일 경우
KAKAO 5글자 답은 5가 나올줄 알았는데 다른사람들의 풀이를 보니 KA 2글자로 답이나오게 되어있는것같다.

난 substing을 비교할때 == 기호를 사용했는데 문자열을 비교할땐 .equals()로 비교하는게 더 정확한 것을 알게되었다.

profile
Let's Coding

0개의 댓글