Notice
Recent Posts
Recent Comments
Link
«   2025/12   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
Tags more
Archives
Today
Total
관리 메뉴

jeongwon

[백준 JAVA] 2941번 - 크로아티아 알파벳 본문

오늘의 문제

[백준 JAVA] 2941번 - 크로아티아 알파벳

jeongwon_ 2022. 6. 9. 15:06

문제:

 

2941번: 크로아티아 알파벳

예전에는 운영체제에서 크로아티아 알파벳을 입력할 수가 없었다. 따라서, 다음과 같이 크로아티아 알파벳을 변경해서 입력했다. 크로아티아 알파벳 변경 č c= ć c- dž dz= đ d- lj lj nj nj š s= ž z=

www.acmicpc.net

 

약식 순서도: 

1) 문자열을 입력 받아 변수에 저장한다. (BufferedReader, String)

2) count 변수를 생성하고, 문자열을 확인한다. (int count, String.charAt()) 

3) 각 경우마다 count를 1씩 더하고 index를 글자 수만큼 건너 뛴다.

 

 

답안: 

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

public class Main {

	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String str = br.readLine();

		int count=0;
		int ln = str.length();
		

		for(int i=0; i<ln; i++) {
			
			char ch = str.charAt(i);
			
			if(ch=='c' && i<ln-1) { //문자 확인 & 범위 확인
				if(str.charAt(i+1)=='='||str.charAt(i+1)=='-') //index 호출
					i++;
				
			}
			
			
			else if(ch=='d'&& i<ln-1) {
				if(str.charAt(i+1)=='-')
					i++;
				else if(i<ln-2) 
					if(str.charAt(i+1)=='z' && str.charAt(i+2)=='=')
						i+=2;
			}
			
			else if((ch=='l'||ch=='n') && i<ln-1) {
				if(str.charAt(i+1)=='j')
					i++;
			}
			
			else if((ch=='s'||ch=='z') && i<ln-1) {
				if(str.charAt(i+1)=='=')
					i++;
			}
			count++;
		}
		
		System.out.println(count);
		br.close();
	}

}

시간 초과에, StringIndexOutOfBounds에 .... 총체적 난국이었다. 

 

 

우선 위와 동일한 코드에 반복문만 while(i<ln)로 변경 및 단항 연산(i++) > 이항연산(i+=2) 했을 때, for 문보다 느려 시간 초과가 나왔다. 

그리고 배열의 범위는 꼭 초과 index를 호출하기 전에 확인해주어야 한다는 것. 

 

도움받은 곳: https://st-lab.tistory.com/68