[ 전화번호 목록 ] : < LV2 / 27125명 >
더보기
#include <string>
#include <vector>
#include <algorithm> // sort()
using namespace std;
bool solution(vector<string> phone_book)
{
bool answer = true;
//
sort(phone_book.begin(), phone_book.end());
//
int cnt = phone_book.size();
for(int i = 0; i < cnt-1; ++i)
{
if(phone_book[i+1].find(phone_book[i]) == 0)
return false;
}
//
return answer;
}
# sort(사전식 정렬)의 특성에 의해 현재 문자열이 다음 문자열의
접두어가 아니면 이후의 모든 문자열을 확인할 필요가 없다.
# str_val.find(str_cmp) 함수는 해당 문자열이 있는 위치를 반환하므로
반환값이 0일 때 str_val은 str_cmp로 시작한다 // startsWith
[ 소수 찾기 ] : < LV2 / 13655명 >
더보기
#include <string>
#include <vector>
//
#include <map> // m.size() // count of key
#include <cmath> // sqrt
#include <algorithm> // next_permutation
using namespace std;
bool IsPrime(int num)
{
if(num == 0 || num == 1)
return false;
//
for(int i = 2; i <= sqrt(num); ++i)
if(num % i == 0)
return false;
//
return true;
}
int solution(string numbers)
{
int answer = 0;
//
map<int, int> m;
vector<bool> v;
string temp = "";
int count = numbers.size();
for(int i = 1; i <= count; ++i)
{
v.clear();
//
for(int j = 0; j < i; ++j)
v.push_back(true);
for(int j = 0; j < count - i; ++j)
v.push_back(false);
//
sort(v.begin(), v.end());
do
{
temp = "";
//
for(int i = 0; i < count; ++i)
if(v[i] == true)
temp += numbers[i];
//
sort(temp.begin(), temp.end());
do
{
int num = stoi(temp);
if(IsPrime(num) == true)
++m[num];
} while (next_permutation(temp.begin(), temp.end()));
} while (next_permutation(v.begin(), v.end()));
}
//
return m.size();
}
# prime number
# permutation, combination
[ 예상 대진표 ] : < LV2 / 4400명 >
더보기
#include <algorithm> // swap
using namespace std;
int solution(int n, int a, int b)
{
int answer = 1;
//
if(a > b)
swap(a, b);
//
while(true)
{
if(a % 2 == 1 && (b - a) == 1)
break;
else
++answer;
//
a += (a % 2);
a /= 2;
//
b += (b % 2);
b /= 2;
}
//
return answer;
}
# a = 2n-1, b = 2n인 경우 루프 종료
'Algorithm' 카테고리의 다른 글
Programmers - 숫자 문자열과 영단어, 위클리 챌린지 1주차, 2주차, 4주차, 5주차 (0) | 2021.09.01 |
---|---|
Programmers - 게임 맵 최단거리, 괄호 변환, 메뉴 리뉴얼 (0) | 2021.06.24 |
Programmers - 카카오프렌즈 컬러링북, 수식 최대화, 튜플 (0) | 2021.06.16 |
Programmers - 문자열 압축, 타겟 넘버, 오픈 채팅방 (0) | 2021.06.15 |
Programmers - 기능 개발, 짝지어 제거하기, 멀쩡한 사각형 (0) | 2021.06.09 |