알고리즘/프로그래머스 문제 풀이
[PG] 카카오 _ 신규 아이디 추천
바켱서
2021. 9. 18. 22:33
https://programmers.co.kr/learn/courses/30/lessons/72410
접근 방법
매우매우 구현 문제라 생각하고 노가다라 생각을 했었다..
하지만 문제를 풀고 나서 다른 사람들의 코드를 보니 나의 코드는 너무나 미숙했었다.
[ 정규식에 대해 알아봐야 할 것 같다. ]
Need Know
- 구현
- 정규식
다른 사람의 Amazing한 풀이
class Solution {
public static String solution(String new_id) {
String answer = "";
String temp = new_id.toLowerCase();
temp = temp.replaceAll("[^-_.a-z0-9]","");
temp = temp.replaceAll("[.]{2,}",".");
temp = temp.replaceAll("^[.]|[.]$","");
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;
}
}
전체 코드 ( Java ) 나의 풀이..
class Solution {
static final int ALPA = 97;
static final int _ALPA = 122;
static final int NUM = 48;
static final int _NUM = 57;
static final int _S = 95;
static final int _END = 46;
static final int _MINUS = 45;
public String solution(String new_id) {
StringBuilder sb = new StringBuilder(new_id.toLowerCase()); // 1단계
// 2단계
StringBuilder sb2 = new StringBuilder();
for(int i=0; i<sb.length(); i++){
char a = sb.charAt(i);
if((a <= _ALPA && a>=ALPA)||(a>= NUM && a<=_NUM) || a == _S || a == _END || a == _MINUS){
sb2.append(a);
}
}
// 3단계
StringBuilder sb3 = new StringBuilder();
for(int i=0; i<sb2.length(); i++){
if(sb2.charAt(i) == _END && sb2.length()-1 != i){
int j = i+1;
while(sb2.charAt(j) == _END){
if(j == sb2.length()-1) {
break;
}
j += 1;
}
i = j-1;
sb3.append(sb2.charAt(i));
}else if(sb2.charAt(i) == _END && sb2.length()-1 == i){
continue;
}else{
sb3.append(sb2.charAt(i));
}
}
// 4단계
if(sb3.length() != 0){
if(sb3.charAt(0) == _END) sb3.deleteCharAt(0);
}
if(sb3.length() != 0) {
if (sb3.charAt(sb3.length() - 1) == _END) sb3.deleteCharAt(sb3.length() - 1);
}
// 5단계
if(sb3.length() ==0){
sb3.append("a");
}
// 6단계
if(sb3.length() >= 16){
sb3.delete(15, sb3.length());
if(sb3.charAt(sb3.length()-1) == _END) sb3.deleteCharAt(sb3.length()-1);
}
// 7단계
if(sb3.length() <= 2){
while(sb3.length() != 3){
sb3.append(sb3.charAt(sb3.length()-1));
}
}
return sb3.toString();
}
}