관리 메뉴

Storage Gonie

(2) [C++, Java] 백준 No.10809 : 알파벳 찾기 본문

알고리즘/백준풀이5. 문자열

(2) [C++, Java] 백준 No.10809 : 알파벳 찾기

Storage Gonie 2019. 4. 25. 17:56
반응형

문제

풀이

# C++

- count에 이어서 find 함수를 사용하면 쉽고 빠르다. 

#include <iostream>

using namespace std;

int main(void)
{
    ios::sync_with_stdio(false);

    string s;
    cin >> s;

    int len;
    len = s.size();

    for (int i = 'a' ; i <= 'z' ; i++) // 'z' 도 포함시키는걸 깜빡하지 말자
    {
        for (int j = 0; j < len ; j++)
        {
            if (s[j] == i)
            {
                cout << j << " ";
                break;
            }
            else if (s[j] != i && j == (len-1))
            {
                cout << -1 << " ";
                break;
            }
        }
    }
}
#include <algorithm>
#include <iostream>
#include <string>
using namespace std;
int main() {
    string s;
    cin >> s;

    for (int i='a'; i<='z'; i++) {
        auto it = find(s.begin(), s.end(), i);
        if (it == s.end()) {
            cout << -1 << ' ';
        } else {
            cout << (it - s.begin()) << ' ';
        }
    }

    cout << '\n';
    

    return 0;
}

# Java

import java.util.*;

public class Main {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        String s = sc.nextLine();
        int[] position = new int[26];
        for (int i=0; i<26; i++) {
            position[i] = -1;
        }
        for (int i=0; i<s.length(); i++) {
            int c = s.charAt(i) - 'a';
            if (position[c] == -1) {
                position[c] = i;
            }
        }
        for (int i=0; i<26; i++) {
            System.out.print(position[i] + " ");
        }
        System.out.println();
    }
}
반응형
Comments