JAVA/JAVA Algorithm

[프로그래머스] 둘만의 암호 (java)

오늘의 진 2023. 6. 20. 16:57
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;


public class Ctest_12 {
	

	
	public static void main(String[] args) {
		
		
		System.out.println(solution("aukks", "wbqd", 5));
	}
	
	
	
	
	
	 public static String solution(String s, String skip, int index) {
		 
		Character [] Alphabet = {'a' , 'b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
	    Character[] strList = new Character[ 26-skip.length() ];
         Map<Character, Boolean> skipList = new HashMap<Character, Boolean>();		
         String answer = "";
		for(int i=0 ; i<skip.length() ; i++){
			skipList.put(skip.charAt(i), true);
		}
		
		int i=0;
       for(char ch : Alphabet){  // 사용 단어 리스트 완성
          if(!skipList.containsKey(ch)){
        	  strList[i] = ch;
        	  i++;
          }
    	   
       }
       
       for(int j=0 ; j<s.length() ; j++){
    	   
           int num = Arrays.binarySearch(strList, s.charAt(j)) + index;  // 해당 숫자의 넘버 
           answer += strList[num];  // 오류가 나는 부분 
           
    	   
       }
     
	        return answer;
	    }

}

처음 이렇게 주었을때 오류 발생 

이유 : 만약 z일때  index =5라면 다시  맨 앞자리의 알파벳부터 살펴야 하는데 

그부분에 대한 처리를 해주지 않아서 ArrayIndexOutIfBoundsException 발생 !

 

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;


class Solution {
	 public String solution(String s, String skip, int index) {
		 
		Character [] Alphabet = {'a' , 'b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
	    Character[] strList = new Character[ 26-skip.length() ];
         Map<Character, Boolean> skipList = new HashMap<Character, Boolean>();		
         String answer = "";
		for(int i=0 ; i<skip.length() ; i++){
			skipList.put(skip.charAt(i), true);
		}
		
		int i=0;
       for(char ch : Alphabet){  // 사용 단어 리스트 완성
          if(!skipList.containsKey(ch)){
        	  strList[i] = ch;
        	  i++;
          }
    	   
       }
       
       for(int j=0 ; j<s.length() ; j++){
    	   
           int num = Arrays.binarySearch(strList, s.charAt(j)) + index;  // 해당 숫자의 넘버 
           answer += strList[num%strList.length    ];
    	   
       }
  
	        return answer;
	    }
}

 요롷게 수정해서 통과 했습니다. 

 

 

 

더 간단한 방법을 찾았는데 char을 int로 생각하고 풀어도 된다. 

	    public String solution(String s, String skip, int index) {
	        String answer = "";

	        for (int i = 0; i < s.length(); i++) {
	           
	        	
	        	char c = s.charAt(i);  // 찾아야할 char 
	            for (int j = 0; j < index; j++) {
	                c += 1;
	                if (c > 'z') {
	                    c -= 26;
	                }
	                if (skip.contains(String.valueOf(c))) {
	                    j--;
	                }
	            }
	            answer += c;

	        
	        }

	        return answer;
	    }