Algorithm/백준

[백준] 2941 with C++

nowkoes 2023. 2. 17. 15:36

문제설명


입출력 예제


개념

 문자열을 크로아티아 알파벳의 규칙에 맞게 변경한 후, 그 개수를 카운팅 하는 문제다. 크로아티아 문자가 생성되는 규칙은 다음과 같다.

  1. 문자 =가 있는 경우
    1. 이전 문자가 c거나 s인 경우 카운트를 2개가 아닌 하나로 한다.
    2. 이전 문자가 z인 경우 카운트를 2개가 아닌 하나로 한다.
    3. 이전 문자가 z이며 d인 경우 카운트를 3개가 아닌 하나로 한다.
  2. 문자 -가 있는 경우
    1. 이전 문자가 c거나 d인 경우 카운트를 2개가 아닌 하나로 한다.
  3. 문자 j가 있는 경우
    1. 이전 문자가 l이거나 n이 경우 카운트를 2개가 아닌 하나로 한다.

풀이

#include<iostream>
#include<string>
using namespace std;

int main()
{
	string str;
	cin >> str;

	int count = 0;

 문자열을 string으로 입력받고, 카운팅할 변수 count를 초기화해준다.

 

	for (int i = 0; i < str.size(); i++)
	{
		count++;
		if (str[i] == '=')
		{
			if (str[i - 1] == 'c' || str[i - 1] == 's')
			{
				count--;
			}

			else if (str[i - 1] == 'z')
			{
				if (str[i - 2] == 'd')
				{
					count--;
				}

				count--;
			}
		}

		else if (str[i] == '-')
		{
			if (str[i - 1] == 'c' || str[i - 1] == 'd')
			{
				count--;
			}
		}

		else if (str[i] == 'j')
		{
			if (str[i - 1] == 'l' || str[i - 1] == 'n')
			{
				count--;
			}
		}
	}

	cout << count;
}

 위에서 언급한 규칙에 맞게 count의 개수를 조절해주고, 그 개수를 출력한다.

 

총합본

#include<iostream>
#include<string>
using namespace std;

int main()
{
	string str;
	cin >> str;

	int count = 0;

	for (int i = 0; i < str.size(); i++)
	{
		count++;
		if (str[i] == '=')
		{
			if (str[i - 1] == 'c' || str[i - 1] == 's')
			{
				count--;
			}

			else if (str[i - 1] == 'z')
			{
				if (str[i - 2] == 'd')
				{
					count--;
				}

				count--;
			}
		}

		else if (str[i] == '-')
		{
			if (str[i - 1] == 'c' || str[i - 1] == 'd')
			{
				count--;
			}
		}

		else if (str[i] == 'j')
		{
			if (str[i - 1] == 'l' || str[i - 1] == 'n')
			{
				count--;
			}
		}
	}

	cout << count;
}

풀이(2)

 위의 풀이는 규칙이 직관적이지만, 코드가 길어 가독성이 조금 떨어지는 거 같다. 따라서 문제 설명에 있는 크로아티아 문자를 배열로 받아, 크로아티아 문자면 문자를 1개로 치환하는 문제 풀이를 고안해보았다.

 

#include <iostream>
#include <string>
using namespace std;

int main()
{
	string cstr[8] = {"c=","c-","dz=","d-","lj","nj","s=","z="};
	string str;
	cin >> str;

	for (int i = 0; i < 8; i++)
	{
		while (true)
		{
			int index = str.find(cstr[i]);

			if (str.find(cstr[i]) == -1)
				break;

			str.replace(index, cstr[i].size(), "#");
		}
	}

	cout << str.length();
}

 

반응형

'Algorithm > 백준' 카테고리의 다른 글

[백준] 1193 with C++  (0) 2023.02.19
[백준] 1316 with C++  (0) 2023.02.18
[백준] 4673 with C++  (0) 2023.02.16
[백준] 2839 C++  (0) 2023.01.24
[백준] 1978 C++  (0) 2023.01.23