본문 바로가기
개발 (언어)/C++

[C++, 백준] 알파벳 찾기

by 진현개발일기 2022. 10. 10.

[2022. 10. 10]

문제

알파벳 소문자로만 이루어진 단어 S가 주어진다. 각각의 알파벳에 대해서, 단어에 포함되어 있는 경우에는 처음 등장하는 위치를, 포함되어 있지 않은 경우에는 -1을 출력하는 프로그램을 작성하시오.

입력

첫째 줄에 단어 S가 주어진다. 단어의 길이는 100을 넘지 않으며, 알파벳 소문자로만 이루어져 있다.

출력

각각의 알파벳에 대해서, a가 처음 등장하는 위치, b가 처음 등장하는 위치, ... z가 처음 등장하는 위치를 공백으로 구분해서 출력한다.

만약, 어떤 알파벳이 단어에 포함되어 있지 않다면 -1을 출력한다. 단어의 첫 번째 글자는 0번째 위치이고, 두 번째 글자는 1번째 위치이다.

 

==================================

두 가지의 방법으로 풀어봤다.

 

1. HashTable 자료구조 활용

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
#include <iostream>
#include <unordered_map>
#include <string>
 
using namespace std;
 
int main(void)
{
    string alphabets = "abcdefghijklmnopqrstuvwxyz";
 
    // :: map은 이진 탐색 트리로 O(logN)이지만 정렬하지 않은 Unordered이기 때문에 팀색 같은 경우 O(1) 상수시간 복잡도임
    unordered_map<charint> alphabetsExist;
 
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
 
    string Inputs;
    cin >> Inputs;
 
    string Result;
 
    for (int i = 0; i < Inputs.length(); i++)
    {
        if (alphabetsExist.find(Inputs[i]) == alphabetsExist.end())
            alphabetsExist.insert(make_pair(Inputs[i], i));
    }
 
    for (int i = 0; i < alphabets.length(); i++)
    {
        if (alphabetsExist.find(alphabets[i]) != alphabetsExist.end())
            Result += to_string(alphabetsExist[alphabets[i]]) + " ";
        else
            Result += "-1 ";
    }
 
    // :: 마지막 띄어쓰기 제거
    Result.pop_back();
 
    cout << Result;
}
cs

 

2. 아스키코드 활용

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
#include <iostream>
 
 
#define Length_Of_Alphabets 26
using namespace std;
 
int main(void)
{
    ios_base::sync_with_stdio(false);
    cout.tie(NULL);
 
   
    // :: 배열 초기화
    int IntArray[Length_Of_Alphabets];
    fill_n(IntArray, Length_Of_Alphabets, -1);
 
    string Input;
    cin >> Input;
 
    int Inputlength = Input.length();
 
    for (int i = 0; i < Inputlength; i++)
    {
        int index = Input[i] - 'a';
 
        if(IntArray[index] == -1)
           IntArray[index] = i;
    }
 
    for (int i = 0; i < Length_Of_Alphabets; i++)
    {
        cout << IntArray[i] << ' ';
    }
 
}
cs

 

728x90

'개발 (언어) > C++' 카테고리의 다른 글

[Modern C++] String  (0) 2024.03.29
[C++] 동적 미로 생성, 우수법 탈출 AI  (0) 2024.03.24
[C++, 백준] 숫자의 합  (0) 2022.10.10
[C++, 백준] 아스키 코드  (0) 2022.10.10
[C++, 백준] 한수  (0) 2022.10.10