[BAEKJOON] 백준 4402: Soundex (C#)

2024. 8. 16. 09:36IT/BaekJoon

문제 링크

https://www.acmicpc.net/problem/4402

 

 

문제

Soundex coding groups together words that appear to sound alike based on their spelling. For example, "can" and "khawn", "con" and "gone" would be equivalent under Soundex coding.

Soundex coding involves translating each word into a series of digits in which each digit represents a letter:

1 represents B, F, P, or V
2 represents C, G, J, K, Q, S, X,  or Z
3 represents D or T
4 represents L
5 represents M or N
6 represents R

The letters A, E, I, O, U, H, W, and Y are not represented in Soundex coding, and repeated letters with the same code digit are represented by a single instance of that digit. Words with the same Soundex coding are considered equivalent.

 

 

입력

Each line of input contains a single word, all upper case, less than 20 letters long.

 

 

출력

For each line of input, produce a line of output giving the Soundex code.

 

 

 

통과한 답안

using System.Text;

namespace _4402
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string input = "";
            while ((input = Console.ReadLine()) != null)
            {
                StringBuilder sb = new StringBuilder();
                char previousDigit = '\0';

                foreach (char c in input)
                {
                    char digit = GetSoundexDigit(c);

                    if (digit != '0' && digit != previousDigit)
                    {
                        sb.Append(digit);
                    }
                    previousDigit = digit;
                }

                Console.WriteLine(sb.ToString());
            }
        }

        private static char GetSoundexDigit(char c)
        {
            switch(c)
            {
                case 'B': case 'F': case 'P': case 'V':
                    return '1';
                case 'C': case 'G': case 'J': case 'K':
                case 'Q': case 'S': case 'X': case 'Z':
                    return '2';
                case 'D': case 'T':
                    return '3';
                case 'L':
                    return '4';
                case 'M': case 'N':
                    return '5';
                case 'R':
                    return '6';
                default:
                    return '0';
            }
        }
    }
}

 

주어진 문자를 Soundex의 형식에 맞게 숫자로 변경하는 문제이다.

 

주어진 조건은 각각의 알파벳에 대한 숫자가 정해져 있고(표기하지 않는 문자도 있다)

반복되는 동일 문자는 제거, 연속된 동일 숫자도 제거 하는 조건이 있다.

 

이에 맞춰서 이전의 알파벳(previousDigit)을 저장하여 비교하는 과정을 구현하였으며,

각각의 알파벳에 맞는 숫자를 가져오기 위해서 switch 문을 사용하였다.