hyunjin

[문자열 - 단어 공부(1157)] string의 transform 본문

알고리즘 연습/백준

[문자열 - 단어 공부(1157)] string의 transform

_h.j 2020. 8. 13. 22:10
728x90

백준/문자열/단어공부(1157) 바로가기

 

 

[문제 요약]

대소문자가 섞인 단어(1,000,000이하의 길이)가 주어질 때 가장 많이 사용된 알파벳을 대문자로 출력

가장 많이 사용된 알파벳이 여러 개 존재하는 경우엔 ?를 출력

 

 

[첫 번째 풀이] 틀림

#include <iostream>
#include <cstdio>
#include <unordered_map>
#include <string>
#include <algorithm>
#include <cstring>
#define endl "\n"
#define _SILENCE_STDEXT_HASH_DEPRECATION_WARNINGS
using namespace std;

int main(void){
	string word;
	string res="";
	unordered_map<char, int> hm;

	cin >> word;
	//getline(cin, word);
	//scanf("%s", word);
	//_strlwr_s(word);
	transform(word.begin(), word.end(), word.begin(),tolower);

	for (int i = 0; i < word.length()/*sizeof(word)/sizeof(char)*/ ; i++) {
		if (!hm.count(word[i]))
			hm.insert(make_pair(word[i], 1));
		else {
			hm[word[i]]++;
		}
	}
	
	int max = 0;
	for (auto it = hm.begin(); it != hm.end(); it++) {
		if (max < it->second) {
			max = it->second;
			res = it->first;
		}
		else if (max == it->second)
			res = "?";
	}

	cout << res;
	//printf("%s\n",res);

	return 0;
}

c++의 stream을 안쓰려고 노력하다 결국 꼬여서 실패.

문제를 해결하는 방식은 맞았으나...

 

 

[두 번째 풀이 소스 코드]

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

using namespace std;

int main(void){
	string word;
	string res="";
	unordered_map<char, int> hm;

	cin >> word;
	transform(word.begin(), word.end(), word.begin(),(int(*)(int))toupper);

	for (int i = 0; i < word.length(); i++) {
		if (!hm.count(word[i]))
			hm.insert(make_pair(word[i], 1));
		else {
			hm[word[i]]++;
		}
	}

	int max = 0;
	for (auto it = hm.begin(); it != hm.end(); it++) {
		if (max < it->second) {
			max = it->second;
			res = it->first;
		}
		else if (max == it->second)
			res = "?";
	}
	cout << res;

	return 0;

}

풀이 전략

1. string을 전부 대문자로 바꾸기

2.알파벳을 인덱스로 하는 map을 사용

3.map 내에서 max를 찾고, max와 같은 것이 있다면 ?로

 

 

[아쉬운 점]

쉬운 문제를 풀면서 이것 저것 해보느라 고생했다.

1. 리턴을 대문자로 해야하는데 계속 소문자로 해서 틀렸다.

2.transform 사용시 toupper가 C 표준 라이브러리와 C++ 표준 라이브러리에 동시에 정의되어 있어

어떤 함수 타입을 overload 할지 결정 못해서 오류가 여러번 났다.

  

[다른 사람 풀이]

바로가기

hash를 안쓰고 알파벳 개수 카운트를 위한 int [26] 배열을 이용하여 푼 방법도 있다.

transform 대신 아스키 코드를 활용한 풀이도 있다.

 

[배운내용]

1. transform ( s.begin(), s.end(), s.begin() ,  touppper/tolower );

헤더파일 : algorithm

특정 구간의 값을 함수를 이용해 변경하면서 다른 구간으로 옮긴다.

 

std transform에서 자주 발생하는 컴파일 오류

해결책 1 

 transform( s.begin() , s.end(), s.begin() , (int(*)(int)))toupper)
 //specific overload

이번엔 이렇게 써야 에러가 발행하지 않았다.

 

해결책 2 

 transform(s.begin(),s.end(),s.begin() , toupper)
 //global scope

 

 

 

728x90