https://school.programmers.co.kr/learn/courses/30/lessons/155652
두 문자열 's'와 'skip', 그리고 자연수 index가 주어질 때, 다음 규칙에 따라 새로운 문자열을 만들어 보자.
- 문자열 s의 각 알파벳을 index만큼 뒤의 알파벳으로 바꿔준다.
- index만큼 뒤의 알파벳이 z를 넘어갈 경우, 다시 a로 돌아간다.
- skip에 있는 알파벳을 제외하고 건너뛰어야 한다.
- 5 ≤ s의 길이 ≤ 50
- 1 ≤ skip의 길이 ≤ 10
- s와 skip은 알파벳 소문자로만 이루어져 있습니다.
- skip에 포함되는 알파벳은 s에 포함되지 않습니다.
- 1 ≤ index ≤ 20
s | skip | index | result |
---|---|---|---|
"aukks" | "wbqd" | 5 | "happy" |
우선 s = "a", index = "3"이라 생각해보면, a의 만큼 뒤에있는 알파벳은 원래라면 ['b', 'c', 'd'] 순 이므로 d가 정답이 된다.
하지만 skip = "bcd"라 가정하면, a의 뒤에있는 알파벳은 ['e', 'f', 'g'] 가 된다.
즉 skip에 있는 알파벳들을 제외한 알파벳 배열을 만든 뒤, 그 배열에서 index만큼 뒤로 밀면 된다.
만약 문자열의 범위를 넘어갈 경우, 그 문자열의 길이만큼 빼주면 되는데, 이때 두 번 이상 넘어갈 경우를 생각해 주어야한다. (예를들어, 배열의 길이가 8, index = 9 일 때 배열의 마지막 원소의 경우, 두 바퀴를 돌아서 맨 첫 번째 원소로 가야한다.)
이를 처리하기 위해, 문자열의 길이만큼 빼주는 것이 아닌, 문자열로 나눈 나머지를 답의 index로 하면 된다.
import java.util.*;
class Solution {
public String solution(String s, String skip, int index) {
StringBuilder answer = new StringBuilder();
List<Character> list = new ArrayList<>();
int i = 0;
for (char c = 'a'; c <= 'z'; c++) {
if (!skip.contains("" + c)) {
list.add(c);
}
}
for (char c : s.toCharArray()) {
int temp = list.indexOf(c) + index;
int alpIndex = checkBoundary(temp, list.size());
answer.append((char) list.get(alpIndex));
}
return answer.toString();
}
private int checkBoundary(int index, int length) {
return index < length ? index : index % length;
}
}
def solution(s, skip, index):
answer = ''
char_set = []
for i in range(26):
temp = chr(i + ord('a'))
if not temp in skip:
char_set.append(temp)
print(char_set)
for alp in s:
new_index = char_set.index(alp) + index
new_index = new_index if new_index < len(char_set) else new_index % len(char_set)
answer += char_set[new_index]
return answer