정답
class Solution {
public String solution(String s, int n) {
//소문자 97 ~ 122
//대문자 65 ~ 90
int idx = 0;
char[] arr = s.toCharArray();
for(char ch : arr){
int a = (int)ch;
if(a >= 65 && a <= 90){
if(a + n > 90){
a += n - 26;
}else{
a += n;
}
}else if(a >= 97 && a <= 122){
if(a + n > 122){
a += n - 26;
}else{
a += n;
}
}
arr[idx] = (char)a;
idx++;
}
return new String(arr);
}
}
분석
참고할 만한 정답
class Caesar {
public String caesar(String s, int _n) {
return s.chars().map(c -> {
int n = _n % 26;
if (c >= 'a' && c <= 'z') {
return 'a' + (c - 'a' + n) % 26;
} else if (c >= 'A' && c <= 'Z') {
return 'A' + (c - 'A' + n) % 26;
} else {
return c;
}
}).mapToObj(c -> String.valueOf((char)c))
.reduce((a, b) -> a + b).orElse("");
}
}
비교 분석
- 스트림을 사용하면 이 경우는 엄청 느리다.
- 여기서 배울점은 아스키코드 대신에 'a' 또는 'A' 같이 사용하는 것과
- n을 26으로 나눈 나머지만 사용하면 n이 어떠한 수가 와도 상관없이 더 해주면 된다.(문제가 변경되어 n이 25이하 이지만 이 기법은 알고 있으면 좋은 기법 같음.)
- if문도 없앨 수 있었고 좀 더 간결한 코드가 되었다.
비교 분석 반영
class Solution {
public String solution(String s, int n) {
int idx = 0;
char[] arr = s.toCharArray();
for(char ch : arr){
int a = (int)ch;
if(a >= 'A' && a <= 'Z'){
a = 'A' + (a - 'A' + n) % 26;
}else if(a >= 'a' && a <= 'z'){
a = 'a' + (a - 'a' + n) % 26;
}
arr[idx] = (char)a;
idx++;
}
return new String(arr);
}
}