💻 IT/📌 ALG

[프로그래머스] 신규 아이디 추천 :: JAVA 풀이

GODSU 2022. 3. 6. 18:14
반응형

 

오늘은 프로그래머스 "신규 아이디 추천" 문제를 풀이해보겠습니다.

 

문제

 

 

반응형

 

 

 

풀이

요번 문제는 문자열 처리 문제입니다. 오랜만에 문자열 공부하는 겸 풀어보았습니다. 문제를 처음 읽고 아무 생각 없이 주어진 스탭 별로 접근을 하였다.

    public String solution(String new_id) {
        
        StringBuffer stb = new StringBuffer(new_id.toLowerCase());

        /*new_id에서 알파벳 소문자, 숫자, 빼기(-), 밑줄(_), 마침표(.)를 제외한 모든 문자를 제거합니다.*/
        /*소문자 97~122, 숫자 48~57, 빼기 45, 밑줄 95, 마침표 46 */
        for (int i = 0; i < stb.length() ; i++) {
        	if(!((stb.charAt(i)-0 >=97 && stb.charAt(i)-0 <=122)
        	  ||(stb.charAt(i)-0 >=48 && stb.charAt(i)-0 <=57)
        	  ||stb.charAt(i)-0 == 45
        	  ||stb.charAt(i)-0 == 46
        	  ||stb.charAt(i)-0 == 95)) {
        		stb.deleteCharAt(i);
        		i--;
        	}
        }
        
        /*new_id에서 마침표(.)가 2번 이상 연속된 부분을 하나의 마침표(.)로 치환합니다.*/
        if(stb.length()>0) {
	        for (int i = 0; i < stb.length(); i++) {
				if( i != stb.length()-1) {
					if(stb.charAt(i)=='.' && stb.charAt(i+1) =='.') {
						stb.deleteCharAt(i);
						i--;
					}
				}
			}
        }
        /*new_id에서 마침표(.)가 처음이나 끝에 위치한다면 제거합니다.*/
        if(stb.length()>0) {
	        if(stb.charAt(0) =='.') {
	        	stb.deleteCharAt(0);
	        }
        }
        if(stb.length()>0) {
	        if(stb.charAt(stb.length()-1) =='.') {
	        	stb.deleteCharAt(stb.length()-1);
	        }
        }
        
        /*new_id가 빈 문자열이라면, new_id에 "a"를 대입합니다.*/
        if(stb.length() ==0) {
        	stb.append('a');
        }

        /*new_id의 길이가 16자 이상이면, new_id의 첫 15개의 문자를 제외한 나머지 문자들을 모두 제거합니다.
          만약 제거 후 마침표(.)가 new_id의 끝에 위치한다면 끝에 위치한 마침표(.) 문자를 제거합니다.*/
        if(stb.length() >= 16) {
        	stb.delete(15, stb.length());
        	if(stb.charAt(stb.length()-1) == '.')
        		stb.deleteCharAt(stb.length()-1);
        }
        
        
        /*new_id의 길이가 2자 이하라면, new_id의 마지막 문자를 new_id의 길이가 3이 될 때까지 반복해서 끝에 붙입니다.*/
        if(stb.length()<=2) {
        	while(stb.length()<3) {
        		stb.append(stb.charAt(stb.length()-1));
        	}
        }
        
        return stb.toString();
    }

저는 stringBuffer를 이용해서 문자열을 수정하면서 문제를 풀었습니다.

정답으로 넘어가긴 했지만.. 가독성, 코드 효율성 모두 좋지 않은 것 같다. 정답을 맞춘 다른 사람 코드를 보니.. 놀라울 뿐이었다

 

 

정규표현식 이용한 답
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;
    }
}

코드를 보면 정규표현식과 replace 함수를 이용하여 간단하게 풀이하였다. 기능 상은 내가 짠 코드랑 별다른 점이 없지만 누가 봐도 가독성 효율성이 좋아 보인다.

 

정규표현식 공부해야겠다..ㅎㅎ

 

 

 

반응형