[백준 13939] Imena (C#, C++) - soo:bak
작성일 :
문제 링크
설명
N개의 문장이 한 줄로 주어질 때, 각 문장에서 이름(첫 글자 대문자, 나머지 소문자, 마지막 글자는 문장부호 가능)의 개수를 세어 문장별로 출력하는 문제입니다.
접근법
단어를 공백으로 분리해 순서대로 확인합니다. 마지막 단어는 ‘.’, ‘?’, ‘!’로 끝날 수 있으므로 문장부호를 제거한 뒤 이름 규칙을 검사합니다.
첫 글자가 대문자이고, 나머지가 모두 소문자면 이름으로 카운트합니다. 문장부호를 만나면 해당 문장의 개수를 출력 목록에 넣고 초기화합니다.
Code
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
using System;
using System.Text;
class Program {
static bool IsName(string w) {
if (w.Length == 0) return false;
if (!char.IsUpper(w[0])) return false;
for (var i = 1; i < w.Length; i++) {
if (!char.IsLower(w[i]))
return false;
}
return true;
}
static void Main() {
var parts = Console.In.ReadToEnd().Split((char[])null, StringSplitOptions.RemoveEmptyEntries);
var idx = 0;
var n = int.Parse(parts[idx++]);
var sb = new StringBuilder();
var cnt = 0;
var outputs = 0;
while (idx < parts.Length && outputs < n) {
var w = parts[idx++];
var end = w.EndsWith(".") || w.EndsWith("?") || w.EndsWith("!");
if (end)
w = w.Substring(0, w.Length - 1);
if (IsName(w)) cnt++;
if (end) {
sb.AppendLine(cnt.ToString());
cnt = 0;
outputs++;
}
}
Console.Write(sb);
}
}
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <bits/stdc++.h>
using namespace std;
typedef vector<int> vi;
bool isName(const string& w) {
if (w.empty()) return false;
if (!isupper(w[0])) return false;
for (size_t i = 1; i < w.size(); i++) {
if (!islower(w[i]))
return false;
}
return true;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n; cin >> n;
vi ans;
int cnt = 0;
string w;
while (cin >> w && (int)ans.size() < n) {
bool end = false;
char last = w.back();
if (last == '.' || last == '?' || last == '!') {
end = true;
w.pop_back();
}
if (isName(w)) cnt++;
if (end) {
ans.push_back(cnt);
cnt = 0;
}
}
for (int v : ans)
cout << v << "\n";
return 0;
}