Algorithm/백준

[백준] 1316 with C++

nowkoes 2023. 2. 18. 17:05

문제설명


입출력 예제


개념

 연속된 문자가 나타났을 때, 그 사이에 교차되는 문자가 있는지 확인하는 문제다. 이를 그림으로 나타내면 다음과 같다.

 

 

 따라서 반복되는 문자열을 모두 지웠을 때 같은 문자가 존재한다면 그룹단어가 아니게 된다는 것을 이용하면 된다.


풀이

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

int main()
{
	int num = 0;
	cin >> num;
	int cnt = 0;

 단어의 개수를 num으로 받고, 그룹 단어 개수를 출력할 cnt를 초기화한다.

 

	for (int i = 0; i < num; i++)
	{
		string str;
		cin >> str;
		bool check = true;
		str.erase(unique(str.begin(), str.end()), str.end());
		sort(str.begin(), str.end());

 문자열을 str로 입력받고, 그룹 단어를 체크할 bool 변수 check를 초기화한다. 여기서 원소를 지우는 함수 erase()중복되지 않는 원소들을 앞자리부터 채우는 함수 unique()를 이용해, 중복된 원소를 지워준다. 그후 문자열 str를 정렬해준다. 

 

출처: cpp reference

 

		for (int j = 0; j < str.size() - 1; j++)
		{
			if (str[j] == str[j + 1])
			{
				check = false;
				break;
			}
		}

		if (check)
			cnt++;
	}

	cout << cnt;
}

 앞선 과정을 통해 정렬한 문자열 str의 길이만큼 반복문을 실행하는데, 만약 j번 째 문자와 j + 1 번 째 문자가 같다면, 그룹 단어가 아니므로 check를 false로 바꾸고 반복문을 탈출한다.

 그후 check가 true인지 false 여부를 확인한 후 cnt의 개수를 조절하면 된다.

 

총합본

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

int main()
{
	int num = 0;
	cin >> num;
	int cnt = 0;

	for (int i = 0; i < num; i++)
	{
		string str;
		cin >> str;
		bool check = true;
		str.erase(unique(str.begin(), str.end()), str.end());
		sort(str.begin(), str.end());

		for (int j = 0; j < str.size() - 1; j++)
		{
			if (str[j] == str[j + 1])
			{
				check = false;
				break;
			}
		}

		if (check)
			cnt++;
	}

	cout << cnt;
}
반응형

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

[백준] 3986 with C++  (0) 2023.02.20
[백준] 1193 with C++  (0) 2023.02.19
[백준] 2941 with C++  (0) 2023.02.17
[백준] 4673 with C++  (0) 2023.02.16
[백준] 2839 C++  (0) 2023.01.24