https://www.acmicpc.net/problem/1159
⏰ 49m
#include <bits/stdc++.h>
using namespace std;
string alp = "abcdefghijklmnopqrstuvwxyz";
int cnt[26];
string print;
int n;
int main(){
cin >> n;
int check = 0;
for (int i = 0; i < n; i++) {
string name;
cin >> name;
for (int j = 0; j < 26; j++) {
if(alp[j] == name[0])
cnt[j]+=1;
}
}
for (int i = 0; i < 26; i++) {
if (cnt[i]>=5) print += alp[i];
else check ++;
}
if (check == 26) cout << "PREDAJA";
else cout << print;
return 0;
}
풀이가 쓸데없이 길어진 것 같은데, 내 기준엔 최선이라 아쉽다.
효율적인 코드가 있을 것이라 본다 ..
check 변수는 각 개수가 5이상인 알파벳이 없다면 카운트해서, 26개가 되면 기권을 출력하도록 한다.
string alp = "abcdefghijklmnopqrstuvwxyz";
이렇게 선언하지 않고 그냥 cnt[26]
의 인덱스가 곧 알파벳이라고 생각을 하고, 번호를 부여하는 방법도 있다. 즉, 문자와 숫자를 맵핑해놓은 아스키코드를 활용한다.
a - 0
b - 1
c - 2
...
'a' + 2 = 'c'
(97 + 2 = 99)
#include <bits/stdc++.h>
using namespace std;
string s, ret;
int main() {
cin >> n;
for (int i = 0; i < n; i++) {
cin >> s;
cnt[s[0] - 'a']++;
}
for (int i = 0; i < 26; i++)
if (cnt[i] >= 5) ret += (i + 'a');
if (ret.size()) cout << ret << "\n";
else cout >> "PREDAJA" << "\n";
}