문자 개수 세기

Subin·2024년 8월 7일

Algorithm

목록 보기
16/69
#include <string>
#include <vector>

using namespace std;

vector<int> solution(string my_string) {
    vector<int> answer(52, 0); //길이가 52이고 모든 값을 0으로 초기화
    // A부터 Z, a부터 z까지 총 52개
    // 대문자 인덱스는 '문자'-'A'
    // 소문자 인덱스는 '문자' - 'a' + 26 
    for(char c: my_string)
    {
        if(c >= 'A' && c <= 'Z')
            answer[c-'A']++;
        else if(c >= 'a' && c <= 'z')
            answer[c-'a'+26]++;
    }
    
    return answer;
}
  • 벡터를 초기화 할 땐, (길이, 이 값으로 초기화)
  • 문자열 아스키코드 값은 굳이 외우기보단 '문자' 이렇게 표현해도 (그래도 'A'=65, 'a'=97은 알아두기)


참고 블로그 : https://googleyness.tistory.com/entry/C-STL-Vector-2%EC%B0%A8%EC%9B%90-%EB%B2%A1%ED%84%B0-%EC%B4%88%EA%B8%B0%ED%99%941D-2D-vector-init

profile
성장하며 꿈꾸는 삶을 살아가고 있는 대학생입니다😊

0개의 댓글