TIL

[241216 TIL] 코딩테스트 공부

yoosorang 2024. 12. 16. 19:54

1️⃣ C++ 알고리즘 코드카타

🔹학습 내용

📌주의할 점

  • 빈칸의 앞뒤 잘 보기
  • 예시의 계산 방식을 잘 보기

 

❗  New Knowledge

  • size() : 배열의 길이 리턴
  • for (auto c : str) { 반복문; } : 배열 반복
  • (char), (int) : 형변환
  • isupper() : 대문자인지
  • tolower() : 대문자 -> 소문자
  • toupper() : 소문자 -> 대문자
#include <string>
#include <vector>

using namespace std;

vector<int> solution(vector<string> cpr) {
    vector<int> answer = {0, 0, 0, 0, 0};
    vector<string> basic_order = {"check", "call", "pressure", "respiration", "repeat"};

    for(int i=0; i<cpr.size(); i++){
        for(int j=0; j<basic_order.size(); j++){
            if(cpr[i] == basic_order[j]){
                answer[i] = j+1;
                break;
            }
        }
    }

    return answer;
}​

 

🔹틀린 문제

 

프로그래머스

SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

대소문자 바꿔서 출력하기 -> 실패


아스키 코드 사용해서 32 빼고 더하는 것까지는 떠올렸는데

형 변환 관련해서 이해가 부족했다.


아래는 좋은 예시

//함수 미사용, 아스키 코드 생각 안 날 때
#include <iostream>
#include <string>

using namespace std;

int main(void)
{
    string str;
    cin >> str;
    for (auto c : str)
    {
        if ('a' <= c && c <= 'z')
            c -= 'a' - 'A';
        else
            c += 'a' - 'A';
        cout << c;
    }
    return 0;
}
//함수 사용
#include <iostream>
#include <string>

using namespace std;

int main(void) {
    string str;
    cin >> str;
    for(char ch : str)
    {
        if(isupper(ch))
            cout << (char)tolower(ch);
        else
            cout <<  (char)toupper(ch);
    }
    return 0;
}

 

🔹참고 코드_게임 인벤토리 정리

#include <string>
#include <vector>

using namespace std;

string solution(vector<string> storage, vector<int> num) {
    int num_item = 0;
    vector<string> clean_storage(storage.size());
    vector<int> clean_num(num.size());

    for(int i=0; i<storage.size(); i++){
        int clean_idx = -1;
        for(int j=0; j<num_item; j++){
            if(storage[i] == clean_storage[j]){
                clean_idx = j;
                break;
            }
        }
        if(clean_idx == -1){
            clean_storage[num_item] = storage[i];
            clean_num[num_item] = num[i];
            num_item += 1;
        }
        else{
            clean_num[clean_idx] += num[i];
        }
    }

    int num_max = -1;
    string answer = "";
    for(int i=0; i<num_item; i++){
        if(clean_num[i] > num_max){
            num_max = clean_num[i];
            answer = clean_storage[i];
        }
    }
    return answer;
}​