728x90
반응형
문제
https://school.programmers.co.kr/learn/courses/30/lessons/160586
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
풀이와 코드
#include <string>
#include <vector>
#include <map>
using namespace std;
vector<int> solution(vector<string> keymap, vector<string> targets) {
vector<int> answer;
map<char, int> countMap; // 알파벳과 최소 횟수를 쌍으로 저장하는 map 데이터 추가
for(char i='A'; i<='Z'; i++){
countMap[i] = 101; // 최소 횟수가 될 수 있는 가장 큰 수(100)보다 큰 값으로 초기화
}
for(int i=0; i<keymap.size(); i++){
for(int j=0; j<keymap[i].size(); j++){
auto countIt = countMap.find(keymap[i][j]);
if(countIt->second > j+1){
countMap[keymap[i][j]] = j+1; // 기존의 횟수보다 적을 경우만 갱신
}
}
}
for(int i=0; i<targets.size(); i++){
int count = 0;
bool isPushBack = false;
for(int j=0; j<targets[i].size(); j++){
auto countIt = countMap.find(targets[i][j]);
if(countIt->second == 101){ // 초기값이라면 keymap에 존재 하지 않음
answer.push_back(-1); // 목표 문자열을 작성할 수 없는 경우임
isPushBack = false;
break;
}else{
count += countIt->second; // 최소 횟수 합산
isPushBack = true;
}
}
if(isPushBack){
answer.push_back(count);
}
}
return answer;
}
728x90
반응형