Dev Hyeri

◖코딩 테스트◗▬▬▬▬▬▬▬▬▬/백준

[백준] 27866 문자와 문자열 (설명/코드/정답)

_hyeri 2024. 6. 4. 23:54

문제 링크 : https://www.acmicpc.net/problem/27866

 

1. 요구 사항 이해

시간, 메모리 제한 : 1초 / 512MB

단어 S와 정수 i가 주어졌을 때, S의 i번째 글자를 출력하는 프로그램을 작성

S의 길이 최대 1000

1 <= i <= |S|

 

 

 

 

2. 설계/검증 

시간 복잡도  최악의 경우  공간 복잡도
O(N) - O(N)

 

 

 

 

3. 정상 코드

import java.util.Scanner;

public class 문자열_문자와문자열 {

    // 단어 S와 정수 i가 주어졌을 때, S의 i번째 글자를 출력하는 프로그램을 작성하시오
    public static void main(String[] args) {

        // 입력을 위한 객체 생성
        Scanner scan = new Scanner(System.in);

        // 첫째 줄에 영어 소문자와 대문자로만 이루어진 단어 S가 주어진다.
        String S = scan.nextLine();
        // 단어의 길이는 최대 1000이다.
        if (S.length() > 1000) {
            System.out.println("단어의 길이는 최대 1000이다.");
            scan.close();
            return;
        }

        // 둘째 줄에 정수 i가 주어진다.
        try {

            int i = Integer.parseInt(scan.nextLine());
            //  (1 <= i <= |S|)
            if (i < 1 || i > S.length()) {
                System.out.println("(1 <= i <= |S|)");
            } else {
                char result = S.charAt(i - 1);
                System.out.println(result);
            }
            scan.close();
        } catch (NumberFormatException e) {
            System.out.println("숫자아님");
        }
    }


}