728x90
반응형
https://programmers.co.kr/learn/courses/30/lessons/42577
내 풀이 (정답)
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
bool solution(vector<string> phone_book) {
bool answer = true;
sort(phone_book.begin(),phone_book.end());
for(int i=0; i<phone_book.size()-1; i++){
int j=i+1;
if(phone_book[i]==phone_book[j].substr(0,phone_book[i].size())){
answer = false;
return answer;
}
}
return answer;
}
다른 풀이 (해시이용) - 문제에서 원한 답 같다
#include <string>
#include <vector>
#include <unordered_map>
using namespace std;
bool solution(vector<string> phone_book) {
bool answer = true;
unordered_map<string, int> hash_map;
for(int i = 0; i < phone_book.size(); i++)
hash_map[phone_book[i]] = 1;
for(int i = 0; i < phone_book.size(); i++) {
string phone_number = "";
for(int j = 0; j < phone_book[i].size(); j++) {
phone_number += phone_book[i][j];
if(hash_map[phone_number] && phone_number != phone_book[i])
answer = false;
}
}
return answer;
}
처음 풀이 (오답)
#include <string>
#include <vector>
using namespace std;
bool solution(vector<string> phone_book) {
bool answer = true;
string front = phone_book[0];
int num = front.size();
for(int i=1; i<phone_book.size(); i++){
if(phone_book[i].substr(0,num) == front){
return false;
}
}
return answer;
}
728x90
반응형
'알고리즘' 카테고리의 다른 글
[재귀함수] 미로찾기 (0) | 2021.11.29 |
---|---|
[프로그래머스/JAVA] 프린터 (0) | 2021.11.16 |
[프로그래머스/C++] 베스트앨범 (0) | 2021.10.13 |
[C++] vector, map (0) | 2021.10.06 |
[프로그래머스/C++] 위장 (0) | 2021.10.06 |