본문 바로가기

Beakjoon/string

[백준] 10809번 알파벳 찾기 (C++)

문제

https://www.acmicpc.net/problem/10809

 

10809번: 알파벳 찾기

각각의 알파벳에 대해서, a가 처음 등장하는 위치, b가 처음 등장하는 위치, ... z가 처음 등장하는 위치를 공백으로 구분해서 출력한다. 만약, 어떤 알파벳이 단어에 포함되어 있지 않다면 -1을 출

www.acmicpc.net

코드

way1(내 풀이)

#include <iostream>
#include <string>

using namespace std;

int main(){
  string s;
  cin >> s;
  int alphabet[26];
  for(int i=0; i<26; i++){
    alphabet[i] = -1;
  }

  for(int i=0; i<s.length(); i++){
    if(alphabet[s[i]-'a'] == -1){
      alphabet[s[i]-'a'] = i;
    }
  }
  
  for(int a : alphabet){
    cout << a << ' ';
  }
  return 0;
}

 

way2

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string s;
    string alphabet = "abcdefghijklmnopqrstuvwxyz";
    cin >> s;

    for (int i = 0; i < alphabet.length(); i++)
    {
        cout << (int)s.find(alphabet[i]) << " ";
    }

    return 0;
}

정리

s.find(찾고싶은 문자(열)) : 찾고싶은 문자(열)의 첫번째 index값을 return하고 없을 경우에는 string::npos을 return 한다. string::npos를 int로 변환했을 때 대응되는 값은 -1이다.

참조

https://modoocode.com/241

https://www.cplusplus.com/reference/string/string/npos/