<프로그래머스 C++> 둘만의 암호 풀이

2026. 5. 21. 10:45Programmers

문제

문자열의 s의 각 알파벳을 index만큼 뒤의 알파벳으로 바꾸는 문제이다.

 

규칙은 다음과 같다.

 

1. z를 넘어가면 다시 a로 돌아온다.

2. skip에 있는 알파벳은 건너뛰고 세지 않는다.

 

 

s skip index index
"aukks" "wbqd" 5 "happy"

 


문제 흐름 파악

'a' 에서 5칸 이동할 때 skip = 'wbqd' 라면

a → b(skip) → c → d(skip) → e → f → g → h
        세지않음       세지않음
count:      1       2       3   4   5

 

skip 문자는 카운트하지 않고 그냥 넘어간다. 따라서 'a'에서 5칸 이동하면 'h'가 된다. 

 

내가 해결한 방식은 한 칸씩 이동하면서 skip이 아닐때만 카운트하는 것이다.


문제 풀이

#include <string>
#include <algorithm>
#include <vector>
using namespace std;

string solution(string s, string skip, int index) {
    string answer = "";

    for(int i = 0; i < s.size(); ++i)
    {
        char cur = s[i];
        int count = 0;

        while(count < index)
        {
            cur = 'a' + (cur - 'a' + 1) % 26;
            if(find(skip.begin(), skip.end(), cur) == skip.end())
                count++;
        }
        answer += cur;
    }
    return answer;
}

코드 흐름

1. s의 각 문자 순회

for(int i = 0; i < s.size(); ++i)
{
    char cur = s[i];
    int count = 0;

 

s 문자열의 문자를 하나씩 꺼내 변수에 저장하고, 이동 횟수를 세는 count를 반복문의 시작에서 0으로 초기화한다.

 

2. 한 칸씩 이동

cur = 'a' + (cur - 'a' + 1) % 26;

알파벳을 한 칸 이동시키는 핵심 코드이다.

 

  • cur - 'a' → 현재 문자를 0~25 숫자로 변환
  • + 1 → 한 칸 이동
  • % 26 → z를 넘어가면 a로 돌아오게
  • 'a' + ... → 다시 문자로 변환

 

3. skip 체크

if(find(skip.begin(), skip.end(), cur) == skip.end())
    count++;

 

find()로 현재 문자가 skip에 없을 때 count를 증가시킨다. skip에 있는 문자면 이동은 하고, 카운트를 올리지는 않는다.

 


핵심 포인트

1. 알파벳 한 칸 이동 로직은 'a' + (cur - 'a' + 1) % 26

2. skip문자는 이동은 하고 카운트에선 제외

3. find(skip.begin(), skip.end(), cur) == skip.end() 로직으로 skip 포함 여부를 확인한다