알고리즘

프로그래머스 시저 암호 (JAVA)

박카스마시며코딩 2022. 7. 9. 15:11

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

 

프로그래머스

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

programmers.co.kr

 

저는 구현을 통해 문제를 해결하였습니다.

각각의 문자를 먼저 알파벳인지 확인하고 알파벳이 아니라면 입력 그대로 리턴하였습니다.

알파벳이라면 n만큼 다음의 알파벳으로 이동시키고, 소문자는 소문자 범위를 대문자는 대문자 범위를 넘어가게 되면 넘어가게된 차이만큼 a에서 더해주었습니다.

 

class Solution {
    public String solution(String s, int n) {
        String answer= cal(s,n);


        return answer;
    }
    private static String cal(String s, int n){
        StringBuilder sb = new StringBuilder();
        for(int i = 0 ; i < s.length(); i++){
            char now = s.charAt(i);
            char nextCh = moveCh(now,n);
            sb.append(nextCh);
        }
        return sb.toString();
    }
    private static final int ALPHA_SIZE = 26;
    private static char moveCh(char ch , int n){
        if( !( (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') )  ){
            return ch;
        }
        // n %= ALPHA_SIZE;
        char nextCh = (char)(ch + n);
        if(ch >= 'a' && ch <= 'z' && (nextCh < 'a' || nextCh > 'z') ){
            int diff = nextCh - 'z'-1;
            nextCh = (char)(diff + 'a');
        }
        if(ch >= 'A' && ch <= 'Z' && (nextCh < 'A' || nextCh > 'Z') ){
            int diff = nextCh - 'Z'-1;
            nextCh = (char)(diff + 'A');
        }
        return nextCh;
    }
}

'알고리즘' 카테고리의 다른 글

백준 1726번 로봇 (JAVA)  (0) 2022.07.11
프로그래머스 조이스틱 (JAVA)  (0) 2022.07.10
백준 1388번 바닥 장식 (JAVA)  (0) 2022.07.08
백준 2151번 거울 설치 (JAVA)  (0) 2022.07.07
프로그래머스 소수 찾기 (JAVA)  (0) 2022.07.06