๐Ÿ“ Coding Test Study/C++

[C++][Programmers][์™„์ „ํƒ์ƒ‰] ์†Œ์ˆ˜์ฐพ๊ธฐ

ibelieveinme 2023. 4. 23. 00:13
728x90

[๋ฌธ์ œ]

https://school.programmers.co.kr/learn/courses/30/lessons/42839?language=cpp 

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr

 

[ํ•ด๊ฒฐ๋ฒ•]

1) ์กฐํ•ฉ์œผ๋กœ ๋ฌธ์ž์กฐํ•ฉ ๋ฝ‘๊ธฐ

2) 1๊ธ€์ž, 2๊ธ€์ž, n๊ธ€์ž์”ฉ ๋ฝ‘๊ธฐ

3) ๋ฝ‘์€ ์ˆ˜์˜ ์†Œ์ˆ˜ํŒ๋ณ„์„ ์œ„ํ•ด ๋ฌธ์ž๋ฅผ intํ˜•์œผ๋กœ ๋ณ€๊ฒฝ

4) ์†Œ์ˆ˜์ธ์ง€ ํŒ๋ณ„. ์†Œ์ˆ˜์ด๋ฉด ์ •๋‹ต ๊ฐœ์ˆ˜ + 1. ์ด ๋•Œ, ์ค‘๋ณตํƒ์ƒ‰ ํŽธ๋ฆฌํ•˜๊ฒŒ ํ•˜๋ ค๊ณ  unordered_set<int> answer; ๋ณ€์ˆ˜๋ฅผ ๋งŒ๋“ค์–ด์„œ ๋„ฃ์—ˆ๋‹ค.

5) answer ์‚ฌ์ด์ฆˆ ๋ฆฌํ„ด

 

[์•Œ์•„๋‘˜ ๊ฒƒ]

1) string to int ํ•จ์ˆ˜

#include <cmath>
stoi("12");

2) unordered_set ์ž๋ฃŒํ˜•

#include <unordered_set>

 unordered_set<int> map; // ์„ ์–ธ
 map.insert(1); // ์‚ฝ์ž…
 map.erase(1); // ์‚ญ์ œ
 map[1] = 2; // ํƒ์ƒ‰ ๋ฐ ์ˆ˜์ •
 map.size(); // ์‚ฌ์ด์ฆˆ ๊ตฌํ•˜๊ธฐ

๊ด€๋ จ๋‚ด์šฉ์€ ์•„๋ž˜ ํฌ์ŠคํŒ… ์ฐธ๊ณ 

https://i-believe-in-me.tistory.com/65

 

[C++] Hash ์ž๋ฃŒ๊ตฌ์กฐ / unordered_map ์‚ฌ์šฉ๋ฒ•

C++์€ ํ•ด์‹œํ…Œ์ด๋ธ”์„ unordered_map ์ด๋ผ๋Š” STL๋กœ ๊ตฌํ˜„ํ•  ์ˆ˜ ์žˆ๋‹ค. unordered_map ํด๋ž˜์Šค ๋‹ค์–‘ํ•œ ๊ธธ์ด์˜ ์š”์†Œ ์‹œํ€€์Šค๋ฅผ ์ œ์–ดํ•˜๋Š” C++ ํ‘œ์ค€ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ ์ปจํ…Œ์ด๋„ˆ ํด๋ž˜์Šค ์— ๋Œ€ํ•œ API `unordered_map` ์ฐธ์กฐ์ž…๋‹ˆ๋‹ค. do

i-believe-in-me.tistory.com

3) ๋ฌธ์ž์—ด ์ผ๋ถ€ ๋ฆฌํ„ด

#include <string>

string str = "0123456789";

str.substr(5); // 56789
str.substr(5, 3); //567

 

[์ฝ”๋“œ]

#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
#include <unordered_set>
using namespace std;

bool isPrime(int a){
    if(a <= 1) return false;
    for(int i = 2; i <= sqrt(a); i++){
        if(a%i == 0) return false;
    }
    return true;
}

int solution(string numbers) {
    int num = 0;
    unordered_set<int> answer;
    
    //์กฐํ•ฉ ๋Œ๋ฆฌ๊ธฐ ์‰ฝ๊ฒŒ ์ •๋ ฌํ•˜๊ธฐ
    sort(numbers.begin(), numbers.end());
        
    //์กฐํ•ฉ์œผ๋กœ ์ˆ˜ ๋ฝ‘๊ธฐ
    do{
        for(int i = 1; i < numbers.size()+1; i++){
            //string -> int๋กœ ๋ฐ”๊พธ๊ธฐ
            //1๊ธ€์ž, 2๊ธ€์ž, n๊ธ€์ž์”ฉ ๋ฝ‘๊ธฐ
            num = stoi(numbers.substr(0, i));
            //๋ฝ‘์€ ์ˆ˜๊ฐ€ ์†Œ์ˆ˜์ธ์ง€ ํŒ๋ณ„ํ•˜๊ธฐ. ์ •๋‹ต ๊ฐฏ์ˆ˜ +1
            if(isPrime(num)) answer.insert(num);
        }
    }while(next_permutation(numbers.begin(), numbers.end()));

    //์†Œ์ˆ˜ ๊ฐฏ์ˆ˜ ๋ฆฌํ„ด
    return answer.size();
}
728x90