Boj - 2941번 : 크로아티아 알파벳

donghani·2024년 8월 18일

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

  1. 내가 한 풀이 방식
    반복문으로 인덱스를 하나하나 확인하고, 특정 크로아티아 알파벳이 나올 때,
    그 다음 인덱스가 길이를 넘지 않는 선에서 확인하고, for문의 i값을 증가시켜서, 나오게 하는 방식
    --> 이유를 모르겠으나 반례가 너무 많이 나옴
package Boj;

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

public class boj_2941 {

	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String str = br.readLine();
		
		int resultLength = 0;
		for(int i = 0; i < str.length(); i++) {
			if(str.charAt(i) == 'c' && i < str.length() - 1) {
					if (str.charAt(i + 1) == '=') {
						i++;
					}
					else if (str.charAt(i + 1) == '-') {
						i++;
					}
			}
			if(str.charAt(i) == 'd' && i < str.length() - 1) {
				if(str.charAt(i + 1) == 'z') {
					if(i < str.length() - 2) {
						if (str.charAt(i+2) == '=' ) {
							i += 2;
						}
					}
					if(str.charAt(i+1) == '-') {
						i++;
					}
				}
			}
			if (str.charAt(i) == 'l' && i < str.length() - 1) {
				if(str.charAt(i + 1) == 'j') {
					i++;
				}
			}
			if (str.charAt(i) == 'n' && i < str.length() - 1) {
				if(str.charAt(i + 1) == 'j') {
					i++;
				}
			}
			if (str.charAt(i) == 's' && i < str.length() - 1) {
				if(str.charAt(i + 1) == '=') {
					i++;
				}
			}
			if (str.charAt(i) == 'z' && i < str.length() - 1) {
				if(str.charAt(i + 1) == '=') {
					i++;
				}
			}
			resultLength++;
		}
		br.close();
		System.out.println(resultLength);
	}
}

2번째 풀이 방식
자바 String API를 사용하기
이 방법은 전에 이것을 풀 때, String.contains()를 사용해 볼려 했으나,
어떻게 하는 지 감이 안잡힌다.
그래도 한번 써보자

package Boj;

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

public class boj_2941 {

	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String str = br.readLine();
		br.close();
		String[] croatiaAlphabet = {"c=", "c-", "dz=", "d-", "lj", "nj", "s=", "z="};
		// 알파벳 목록을 귀찮게 일일히 if문을 쓰지말고
		
		int count = 0;
		for(String val : croatiaAlphabet) {
			while(str.contains(val)) { //포함되어있으면
				str = str.replace(val, "A"); //하나의 글자로 세기로 했던 문제 규칙을 지키게 하기
			}
		}
		count += str.length();
		System.out.println(count);
	}
}

해당 코드로 하니까 정답이 나왔다.
이제 반례에 대해서 정리해보자

  1. 입력 : dz=dz= 2. 오류 났었음
profile
컴퓨터 공학과 이방인

0개의 댓글