[c++/알고리즘] 백준 10809 - 배열초기화

corncheese·2021년 7월 13일
0

알고리즘문제풀이

목록 보기
2/31

c++ 배열 초기화

std::fill_n(배열명(배열의메모리주소), 변경하려는 원소의 갯수 , 변경 값);

//백준 10809번 알파벳찾기

#include <iostream>
#include <algorithm>

using namespace std;

int main(){
    int index[26];
    char S[101];

    cin >> S;
    fill_n(index, 26, -1);

    for(int i=0; S[i] != '\0'; i++){
        if(index[S[i]-97] == -1) {
            index[S[i] - 97] = i;
        }
    }

    for(int i=0; i<=25; i++){
        cout << index[i] << " ";
    }


}
  • 알파벳 아스키코드를 이용해 인덱스배열을 만들고, 값을 -1로 초기화
  • 입력받은 문자열의 시작점을 인덱스배열의 값으로 저장한다.

검색하며 찾은 더욱 쉽게 풀은 코드 : STL 사용!

String STL의 find함수는 입력 문자열이 최초로 등장하는 위치의 인덱스를 반환하는 함수이다.

  • 문자열을 찾지못했다면 -1이 리턴되고, 찾았을 경우 위치값이 리턴된다.
#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;
}

0개의 댓글