코딩테스트/Java

(2021카카오) 신규 아이디 추천 Java

SK_MOUSE 2021. 2. 22. 13:01
반응형

 

정규표현식으로 문제풀이를 하기위해서 좀 알아보았다.

 

https://postitforhooney.tistory.com/entry/JavaRegex-%EC%9E%90%EB%B0%94-%EC%A0%95%EA%B7%9C%ED%91%9C%ED%98%84%EC%8B%9D%EC%97%90-%EB%8C%80%ED%95%B4%EC%84%9C-%EA%B3%B5%EB%B6%80%ED%95%98%EA%B3%A0-%EC%98%88%EC%A0%9C-%EB%A7%8C%EB%93%A4%EA%B8%B0

 

문제에서 요구한 조건을 그대로 순서대로 구현한 필자의 코드이다.

 

2번은 Pattern, Matcher을 이용하여 틀에 맞지않는부분을 잘라버리는 방식이다.

class Solution {
    public String solution(String new_id) {
        String answer = "";

        new_id=new_id.toLowerCase();
        //2 정규식
        String temp="";
        String pattern = "^[0-9a-z\\_\\-\\.]*$"; //숫자만
        for(int i =0; i<new_id.length(); i++){
            String s =new_id.substring(i,i+1);
            if(s.matches(pattern)){
                temp += s;
            }
        }
        new_id=temp;
        //3
        for(int i =0; i<new_id.length()-1; i++){
            if(new_id.charAt(i)=='.' && new_id.charAt(i+1)=='.'){
                new_id=new_id.substring(0,i+1) + new_id.substring(i+2);
                i=0;
            }
        }
        //4
        while(new_id.length()>=1&&new_id.charAt(0)=='.') new_id=new_id.substring(1);
        while(new_id.length()>=1&&new_id.charAt(new_id.length()-1)=='.') new_id=new_id.substring(0,new_id.length()-1);
        //5
        if(new_id.equals("")){
            new_id="a";
        }
        //6
        if(new_id.length()>=16) new_id=new_id.substring(0,15);
        if(new_id.charAt(new_id.length()-1)=='.') new_id=new_id.substring(0,new_id.length()-1);

        //7
        StringBuilder new_idBuilder = new StringBuilder(new_id);
        while(new_idBuilder.length()<=2){
            char c = new_idBuilder.charAt(new_idBuilder.length()-1);
            new_idBuilder.append(c);
        }
        new_id = new_idBuilder.toString();


        return new_id;
    }
}

전체적으로 StringBuilder를 사용했으면 조금 더 효율적인 코드가 되었을것이다.

3번조건에서 '.'이 2개이상 연속되는 경우를 while문으로 검사하되, i=0로 다시 처음부터 검사하는 방식으로 구현했다.

4번조건에서 '.'이 처음이나 끝에 있는경우 if문이 아니라 while문으로 구현해야한다.

 

 

다른사람의 코드이다.

2번조건은 replaceAll을 사용하여 자르는 과정을 대체 ""와 같이 공백문자열로 하였다.

3번조건은 '.'이 2개이상 연속되는 경우=> [.]{2,} 와 같이 표현한다. 정규표현식을 공부하자.

4번조건은 '.'이 처음이나 에 있는경우 [.]$  |(or) ^[.] 로 표현한다.

class Solution {
    public String solution(String new_id) {
        String answer = "";
        String temp = new_id.toLowerCase();

        temp = temp.replaceAll("[^-_.a-z0-9]","");
        System.out.println(temp);
        temp = temp.replaceAll("[.]{2,}",".");
        temp = temp.replaceAll("^[.]|[.]$","");
        System.out.println(temp.length());
        if(temp.equals(""))
            temp+="a";
        if(temp.length() >=16){
            temp = temp.substring(0,15);
            temp=temp.replaceAll("^[.]|[.]$","");
        }
        if(temp.length()<=2)
            while(temp.length()<3)
                temp+=temp.charAt(temp.length()-1);

        answer=temp;
        return answer;
    }
}

 

반응형