[프로그래머스] 둘만의 암호 C++
in Study on Coding Test
전형적인 string 문제
정답제출코드
#include <string>
#include <vector>
using namespace std;
bool Have(string s, char c)
{
int len = s.length();
for (int i = 0; i < len; ++i)
{
if (s[i] == c)
return true;
}
return false;
}
string solution(string s, string skip, int index) {
int len = s.length();
for (int i = 0; i < len; ++i)
{
int count = 1;
while (count <= index)
{
if (s[i] == 'z')
s[i] = 'a';
else
s[i] += 1;
if (!(Have(skip, s[i])))
count++;
}
}
return s;
}
- C++의 char 연산에서 아스키코드 값의 원리를 통해 +1을 해주면 다음 문자로 넘어가는 것을 이용한다.
- 다만, 변환하기 전에 해당 문자가 z일 경우 a로 보낸다.
- 카운트를 세주어 index 값보다 작거나 같을 경우 위 과정을 반복한다.
- 변환 결과가 skip 문자열에 있을 경우 카운트를 세지 않는다.