728x90
반응형
🔗 문제 링크
https://school.programmers.co.kr/learn/courses/30/lessons/64065
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
728x90
👩💻 코드
#include <string>
#include <vector>
#include <map>
#include <algorithm>
#include <cctype>
using namespace std;
vector<int> solution(string s) {
vector<int> answer;
vector<int> tempVec;
string tempStr;
map<int, vector<int>> tuples;
for (char c : s) {
if (isdigit(c)) {
tempStr += c;
} else if (c == ',' || c == '}') {
if (!tempStr.empty()) {
tempVec.push_back(stoi(tempStr));
tempStr.clear();
}
if (c == '}') {
if (!tempVec.empty()) {
tuples[tempVec.size()] = tempVec;
tempVec.clear();
}
}
}
}
for(const auto &tuple : tuples){
for(int number : tuple.second){
if(find(answer.begin(), answer.end(), number) == answer.end()){
answer.push_back(number);
}
}
}
return answer;
}
📝 풀이
주어진 문자열에서 하나의 튜플을 추출해 map의 key값으로 튜플 원소의 개수와 value에는 튜플 원소 vector를 넣었다.
문자열을 파싱하는 방법은 숫자인 경우 문자열로 저장해두었다가 ','이나 '}'가 나오면 저장된 숫자 문자열을 int로 변환해 vector에 추가한다.
'}'의 경우에는 map에 vector도 추가해주어야 한다.
이렇게 map에 분류 후 반복문을 돌면서 기존의 answer에 존재하지 않은 원소일 경우만 answer에 추가하면 된다.
이 문제 풀이의 핵심은 적은 원소를 가진 튜플부터 확인해야 한다는 점이다.
728x90
반응형
'코딩테스트 > 프로그래머스' 카테고리의 다른 글
[프로그래머스] [1차] 뉴스 클러스터링 (0) | 2024.08.08 |
---|---|
[프로그래머스] 피로도 (0) | 2024.08.03 |
[프로그래머스] [1차] 캐시 (0) | 2024.07.28 |
[프로그래머스] 행렬의 곱셈 (0) | 2024.07.27 |
[프로그래머스] 할인 행사 (0) | 2024.07.25 |