Post

[BaekJoon] #10809 - 알파벳 찾기 [Java][C++]

[BaekJoon] #10809 - 알파벳 찾기 [Java][C++]

문제 링크


1. 아이디어

주어진 문자열에 대해 알파벳 소문자 각각이 등장하지 않으면 -1, 등장하면 가장 처음 등장한 인덱스를 출력해야 한다. 정수와 문자 간 타입 변환을 활용하면 해결할 수 있다.


2. 복잡도

접근시간공간
풀이$O(N)$$O(N)$

($N$ = s의 길이)


3. 코드

풀이 [Java][C++]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import java.io.*;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb = new StringBuilder();

        String s = br.readLine();
        for (int i = 0; i < 26; i++) {
            sb.append(s.indexOf((char) (i + 'a'))).append(" ");
        }

        System.out.println(sb);
    }
}

String의 indexOf 메서드를 활용해서 간단하게 구현했다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);

    string s;
    cin >> s;

    for (int i = 0; i < 26; i++) {
        int pos = s.find((char)(i + 'a'));
        cout << pos << ' ';
    }
}

find 함수를 활용해서 간단하게 구현했다.


This post is licensed under CC BY 4.0 by the author.