(Java)프로그래머스 - 둘만의 암호

윤준혁·2024년 3월 9일

나의 풀이

import java.util.*;

class Solution {
    public String solution(String s, String skip, int index) {
        String answer = "";
        List<Character> list = new ArrayList<>();
        
        for (char c : skip.toCharArray()) { // 1
            list.add(c);
        }
        
        for (int i = 0; i < s.length(); i++) { // 2
            int c = s.charAt(i);
            int value = c;
            int count = 0;
            
            while (count < index) { // 3
                value++;
                if (value > 122) value = 97;
                if (!list.contains((char)value)) count++; // 4
            }
            
            answer += (char)value;
        }
        
        return answer;
    }
}

과정

  1. 문자열 skip에 담겨있는 문자를 char형태로 하나씩 list에 넣어준다
  2. 문자열 s의 i번째 문자를 c로 두고, c가 바뀌면 안되니까 value를 선언해주고, 카운트를 세줄 정수 count를 선언
  3. index만큼 밀기 위해 while문을 선언. value를 증가시키고, 122가 넘어가면 97로 초기화(ASCII Table 참조)
  4. list에 value의 문자값이 없을때만 count를 증가(있으면 하나 더 증가시키기 위해)

ASCII Table(아스키 코드 표)

다른 사람 풀이

class Solution {
    public String solution(String s, String skip, int index) {
        StringBuilder answer = new StringBuilder();

        for (char letter : s.toCharArray()) {
            char temp = letter;
            int idx = 0;
            while (idx < index) {
                temp = temp == 'z' ? 'a' : (char) (temp + 1);
                if (!skip.contains(String.valueOf(temp))) {
                    idx += 1;
                }
            }
            answer.append(temp);
        }

        return answer.toString();
    }
}

0개의 댓글