Patrick's Devlog

[BOJ/C++] 행복한지 슬픈지(10769번) 본문

Study/Algorithms Practice

[BOJ/C++] 행복한지 슬픈지(10769번)

Patrick_ 2022. 6. 28. 18:50

1. 문제 개요

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

 

10769번: 행복한지 슬픈지

승엽이는 자신의 감정을 표현하기 위해서 종종 문자 메시지에 이모티콘을 넣어 보내곤 한다. 승엽이가 보내는 이모티콘은 세 개의 문자가 붙어있는 구조로 이루어져 있으며, 행복한 얼굴을 나

www.acmicpc.net

1-1. 설명

승엽이는 이모티콘을 좋아해서 메시지에 종종 이모티콘을 붙인다. 행복할 땐 :-)를, 슬플땐 :-(를 보낸다. 혜성이는 승엽이의 이모티콘을 싫어하므로 승엽이의 문자가 오면 전체적인 분위기만 판단해서 알려주는 프로그램을 작성하고자 한다.

1-2. 제한 사항

 - 첫줄에 최소 1개, 최대 255개 문자 입력

 - 이모티콘 포함되지 않을 시 none

 - 행복한 이모티콘과 슬픈 이모티콘 수가 동일할 시 unsure

 - 행복한 이모티콘이 슬픈 이모티콘 수보다 많을 시 happy

 - 슬픈 이모티콘이 행복한 이모티콘 수보다 많을 시 sad


2. 구현

2-1. 설명

단순하게 C++의 find를 사용하여 이모티콘의 개수를 파악하고 카운트를 세어 각 카운트에 맞는 값을 출력하게 한다. 

2-1. 소스 코드

#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

int main(void) {
	string inputString;
	getline(cin, inputString); // 한 줄 입력

	int happy = 0, sad = 0;
	int happyCount = 0, sadCount = 0;
	string happyStr = ":-)", sadStr = ":-(";

	while (true) {
		if (inputString.find(happyStr, happy) != string::npos) { // 행복 이모티콘이 존재할 때
			happyCount += 1; // 1 증가
			happy = inputString.find(happyStr, happy) + happyStr.length(); // 이모티콘 길이만큼 인덱스 변경
		}
		if (inputString.find(sadStr, sad) != string::npos) { // 슬픈 이모티콘이 존재할 때 
			sadCount += 1; // 1 증가
			sad = inputString.find(sadStr, sad) + sadStr.length(); // 이모티콘 길이만큼 인덱스 변경 
		}
		if ((inputString.find(happyStr, happy) == string::npos) && (inputString.find(sadStr, sad) == string::npos)) break;
		// 이모티콘이 존재하지 않으면 반복문 종료
	}

	if (happyCount == 0 && sadCount == 0) cout << "none" << endl;
	else if (happyCount == sadCount) cout << "unsure" << endl;
	else if (happyCount > sadCount) cout << "happy" << endl;
	else cout << "sad" << endl;
}