[BOJ] 2941번: 크로아티아 알파벳 (C#)

Pilgyeong_G·2020년 7월 28일
0

BOJ

목록 보기
8/9
post-thumbnail

BOJ 2941: 크로아티아 알파벳

📜Problem

solved.ac : Silver V
https://www.acmicpc.net/problem/2941

📝Solving

입력으로 받은 문자열을 반복문으로 문자 하나씩 체크를 해봐야 하는 문제다.

반복문을 돌리는 방법은 여러가지가 있지만, 나는 확인해야할 문자를 2자리 문자열과 3자리 문자열로 나눠서 구현하였다.

먼저 반복문을 돌리면서 현재 문자가 위치한 지점보다 뒤에 문자들이 더 있는지 확인해야 한다. 뒤에 더 이상 문자가 없는데 확인하려고 하면 예외가 발생하기 때문이다. 그렇기 때문에 i + (n자리 문자열의 자릿수) < input.Length 조건을 이용하여 뒤에 문자가 더 있는지를 확인한다.

n자리의 문자열을 가져올 수 있다면 Substring 메서드로 input 문자열에서 i번째 문자에서 n 길이만큼 문자열을 가져온다. 가져온 문자열을 foreach문을 사용하여 미리 나열한 문자열들과 비교한다. 여기서 미리 나열한 문자열은 TwoThree이름의 Enumerable<string> 변수에서 가져온다.

만약 리스트 중에 일치하는 문자열이 있다면 count++연산을 해당 문자열의 길이만큼 하지 않기 위해 skeepChar의 값을 n자리 문자열의 자릿수 - 1로 넣어주고 foreach문을 빠져나간다.

또한 2자리 문자열 체크 로직과 3자리 문자열 체크 로직에서 2자리 문자열 체크 로직에서 일치하는 문자열을 찾아서 match의 값이 true가 되었을 경우, 불필요한 연산을 피하기 위해 다음 if문에서 !match 조건을 확인한다.

🚀Full code

using System;
using System.Collections.Generic;

internal static class Program
{
    private static void Main() =>
        Console.WriteLine(CroatianAlphabet.CalclateAlphabetCount(Console.ReadLine()));
}

public static class CroatianAlphabet
{
    private static readonly IEnumerable<string> Two = new List<string>
    {
        "c=", "c-", "d-", "lj", "nj", "s=", "z="
    };

    private static readonly IEnumerable<string> Three = new List<string>
    {
        "dz="
    };

    public static int CalclateAlphabetCount(string input)
    {
        int count = 0;
        bool match = false;
        int skeepChar = 0;

        for (int i = 0; i < input.Length; i++)
        {
            if (i + 1 < input.Length)
            {
                string check = input.Substring(i, 2);
                foreach (string target in Two)
                {
                    if (target == check)
                    {
                        match = true;
                        skeepChar = 1;
                        break;
                    }
                }
            }
            if (!match && i + 2 < input.Length)
            {
                string check = input.Substring(i, 3);
                foreach (string target in Three)
                {
                    if (target == check)
                    {
                        match = true;
                        skeepChar = 2;
                        break;
                    }
                }
            }

            if (match)
            {
                i += skeepChar;
                match = false;
                skeepChar = 0;
            }
            count++;
        }

        return count;
    }
}

0개의 댓글