Little Jay

[C++] 백준 3613번 - Java vs C++ 본문

알고리즘/BOJ

[C++] 백준 3613번 - Java vs C++

Jay, Lee 2022. 7. 1. 17:31

처리해야하는 항목은 다음과 같다

  • 문장의 맨 앞에 '_' 가 오는 경우
  • 문장의 맨 뒤에 '_' 가 오는 경우
  • 문장의 만 앞이 대문자인 경우
  • '__' 같이 언더스코어가 연속적으로 나오는 경우
  • 대문자와 '_'가 복합적으로 나오는 경우

정도를 에러처리 해주면 나머지 구현은 쉽다. Python으로 풀면 더 간단할텐데 C++이라 코드도 길어지고 시간도 오래 걸렸다. toJava 함수에서 위험한 구간이 있는데 s[i + 1] == '_'인 경우를 체크해주는건데 메모리를 잘못 건드려서 seg fault가 날 수 있지 않을까를 생각해봤는데 그 경우의 수는 문장의 마지막에 '_'가 오는 경우이기 때문에 이미 체크를 해서 안전하게 넘어갈 수 있는 것 같다. 

#include <bits/stdc++.h>
#define endl '\n'
using namespace std;

string s;
int cs = 0;
int js = 0;

void toCplusplus() {
	vector<string> v;
	int start_index = 0;
	for (int i = 0; i < s.size(); i++) {
		if (s[i] > 64 && s[i] < 91) {
			string temp = s.substr(start_index, i - start_index);
			v.push_back(temp);
			start_index = i;
		}
	}
	string temp = s.substr(start_index, s.size() - start_index);
	v.push_back(temp);
	
	cout << v[0];
	for (int i = 1; i < v.size(); i++) {
		cout << "_";
		v[i][0] = v[i][0] + 32;
		cout << v[i];
	}
}

void toJava() {
	vector<string> v;
	int start_index = 0;
	for (int i = 0; i < s.size(); i++) {
		if (s[i] == '_') {
			if (s[i + 1] == '_') {
				cout << "Error!" << endl;
				exit(0);
			}
			string temp = s.substr(start_index, i - start_index);
			v.push_back(temp);
			i++;
			start_index = i;
		}
	}
	string temp = s.substr(start_index, s.size() - start_index);
	v.push_back(temp);

	cout << v[0];
	for (int i = 1; i < v.size(); i++) {
		v[i][0] = v[i][0] - 32;
		cout << v[i];
	}
}

int main() {

	ios::sync_with_stdio(false);
	cin.tie(0); cout.tie(0);

	cin >> s;
	int len = s.size();

	for (int i = 0; i < len; i++) {
		if (s[i] == '_') cs++;
		if (s[i] > 64 && s[i] < 91) js++;
	}

	if (s[0] == '_' || (s[0] > 64 && s[0] < 91)) {
		cout << "Error!" << endl;
		return 0;
	}

	if (s[s.size() - 1] == '_') {
		cout << "Error!" << endl;
		return 0;
	}

	if (cs > 0 && js > 0) {
		cout << "Error!" << endl;
	}
	else if (js == 0 && cs > 0) {
		toJava();
	}
	else if (js > 0 && cs == 0) {
		toCplusplus();
	}
	else if (js == 0 && cs == 0) {
		cout << s << endl;
	}
	else {
		cout << "Error!" << endl;
	}


	return 0;
}
Comments