백준 1316 - 그룹 단어 체커 (Silver V)
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
// 백준 1316 - 그룹 단어 체커 (Silver V)
// https://www.acmicpc.net/problem/1316
// 문제 설명
// 그룹 단어: 단어에 존재하는 모든 문자가 연속해서 나타나는 경우
// 예) "ccazzzzbb" → 그룹 단어 O (c, a, z, b 모두 연속)
// "abab" → 그룹 단어 X (a와 b가 번갈아 등장)
// "aba" → 그룹 단어 X (a가 연속하지 않음)
// N개의 단어를 입력받아 그룹 단어의 개수를 출력하시오.
// 입력
// 첫째 줄: 단어의 개수 N (1 ≤ N ≤ 100)
// 둘째 줄~: N개의 단어 (알파벳 소문자, 길이 ≤ 100)
// 출력
// 그룹 단어의 개수
// 입출력 예
// 입력: 출력:
// 3 3
// happy
// new
// year
//
// 입력: 출력:
// 4 1
// aba
// abab
// abcabc
// a
#include <iostream>
#include <string>
using namespace std;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
int answer = 0;
for (int i = 0; i < n; i++)
{
string word;
cin >> word;
// 풀이 작성
bool visited[26] = {};
char prev = 0;
bool isGroup = true;
for(char c : word)
{
if(c != prev)
{
if(visited[c- 'a'])
{
isGroup = false;
break;
}
visited[c-'a'] = true;
prev = c;
}
}
if(isGroup) answer++;
}
cout << answer << "\n";
return 0;
}
// [최적화] 비트마스크 사용 — bool[26] 배열 대신 int 1개로 처리
// bool[26]: 26바이트 배열 접근 vs int: 4바이트 단일 변수 비트 연산
// 시간복잡도 동일 O(N×L)이지만 메모리 접근 횟수 감소
// bool isGroupWord(const string& word)
// {
// int visited = 0; // 비트 0~25 = 알파벳 a~z
// char prev = 0;
//
// for (char c : word)
// {
// if (c != prev)
// {
// int bit = 1 << (c - 'a'); // 해당 문자의 비트 위치
// if (visited & bit) return false; // 이미 등장한 문자면 종료
// visited |= bit; // 비트 ON
// prev = c;
// }
// }
// return true;
// }
//
// int main()
// {
// ios_base::sync_with_stdio(false);
// cin.tie(nullptr);
//
// int n;
// cin >> n;
//
// int answer = 0;
// for (int i = 0; i < n; i++)
// {
// string word;
// cin >> word;
// if (isGroupWord(word)) answer++;
// }
//
// cout << answer << "\n";
// return 0;
// }
이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.