본문 바로가기

코딩테스트/프로그래머스

[프로그래머스] 둘만의 암호

728x90
반응형


🔗 문제 링크

https://school.programmers.co.kr/learn/courses/30/lessons/155652

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr


👩‍💻 코드

#include <string>
#include <vector>
#include <algorithm>

using namespace std;

string solution(string s, string skip, int index) {
    string answer = "";
    string alphabet = "abcdefghijklmnopqrstuvwxyz";
    vector<char> cycle;
    
    for(const auto& letter : alphabet){
        if(skip.find(letter) == string::npos) {
            cycle.push_back(letter);
        }
    }
    
    for(const auto& letter : s){
        int newIndex = (find(cycle.begin(), cycle.end(), letter) - cycle.begin() + index) % cycle.size();
        
        answer += cycle[newIndex];
    }
    
    return answer;
}

📝 풀이

먼저 skip의 알파벳을 제외한 하나의 cycle 벡터를 만들었다.

아스키코드를 이용해서 만들까 하다가 string으로 선언하는게 더 간단할거 같아서 이 방식으로 했다.

기존 문자열 s의 문자 index를 cycle에서 찾은 후 문제에 주어진 index 값만큼 뒤로 보냈다.

앞으로 다시 돌아가는 경우를 위해 cycle.size()로 나눈 나머지를 newIndex로 계산했다.

cycle의 newIndex의 문자를 answer에 추가해주면 끝!

728x90
반응형