[프로그래머스] 신규 아이디 추천 java

이승훈·2021년 6월 22일
0

알고리즘

목록 보기
2/2

문제

Idea

정규표현식을 이용해 각 조건의 문자를 replaceAll method를 통해 제거하는 방식으로 진행

Regular Express

"[a-z]" : a~z까지의 소문자
"[^a-z]" : a~z까지의 소문자를 제외한 모든경우
"[0-9]" : 숫자
"[^0-9]" : 숫자를 제외한 모든 경우

String step2 = step1.replaceAll("[^a-z0-9-_.]", "");
따라서 소문자, 숫자, -, _, . 를 제외한 모든 문자를 제거하는 코드이다.

"^[.]" ^를 []좌측에 작성할 경우 ~로 시작한다 라고 이해하면 됩니다.
"[.]$" $를 []우측에 작성할 경우 ~로 마친다 라고 이해하면 됩니다.

따라서 step4 = step3.replaceAll("^[.]|[.]$", ""); // .로 시작하거나 .으로 끝난다면 그 부분을 제거하는 코드이다.

solution

class Solution {
    public String solution(String new_id) {
        
        
        // step 1
        String step1 = new_id.toLowerCase(); //소문자 변환
        System.out.println("step1 : " + step1);
        
        //step 2
        String step2 = step1.replaceAll("[^a-z0-9-_.]", ""); // 소문자, 숫자, -, _, . 을 제외한 문자 삭제
        
        System.out.println("step2 : " + step2);
        
        //step 3
        String step3 = step2.replaceAll("[.]{2,}", "."); // .이 2회이상 반복되는 부분을 .로 치환
        System.out.println("step3 : " + step3);
        
        
        String step4 = step3;
        
        //step 4
        if(step4.length() == 1 && step4.charAt(0) == '.'){// .만 유일하게 남았다면 빈문자열로 변경
            step4 = "";
        } else{ 
            
          step4 = step3.replaceAll("^[.]|[.]$", ""); // .로 시작하거나 .으로 끝난다면 그 부분 삭제
            
        }
        System.out.println("step4 : " + step4);
        String step5 = step4;
        if("".equals(step4)) {// step 5 
            step5 = "a";
        } else if(step4.length() >= 16){//step6
            step5 = step4.substring(0, 15);
        
            step5 = step5.replaceAll("[.]$", "");

        }
        System.out.println("step5 : "+step5);
        
        //step 7
        String lastChar = Character.toString(step5.charAt(step5.length() - 1));
        while(step5.length() <= 2) {
            step5+=lastChar;
        }
        
        
        return step5;
    }
}

0개의 댓글