elesis's haunt
프로그래머스 레벨1) 신규 아이디 추천 본문
class Solution {
public String solution(String new_id) {
String word = new_id;
String result = "";
//1
word = word.toLowerCase();
//2
word = word.replaceAll("\\~|\\!|\\@|\\#|\\$|\\%|\\^|\\&|\\*|\\(|\\)|\\=|\\+|\\[|\\{|\\]|\\}|\\:|\\?|\\,|\\<|\\>|\\/", "");
//3
word = word.replaceAll("\\.+", ".");
//4
word = word.replaceAll("^\\.", "");
word = word.replaceAll("\\.$", "");
//5
if(word.length()==0) word="a";
//6
if(word.length()>15) {
word = word.substring(0, 15);
word = word.replaceAll("\\.$", "");
}
//7
if(word.length()<=2) {
String dup = word.substring(word.length()-1, word.length());
result = word;
for(int i=word.length(); i<3; i++) {
result += dup;
}
} else {
result = word;
}
return result;
}
}
* 정규식, charAt()의 사용
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;
}
}
* 정규식, 객체지향적인, Method Chain, charAt()의 사용
lass Solution {
public String solution(String new_id) {
String s = new KAKAOID(new_id)
.replaceToLowerCase()
.filter()
.toSingleDot()
.noStartEndDot()
.noBlank()
.noGreaterThan16()
.noLessThan2()
.getResult();
return s;
}
private static class KAKAOID {
private String s;
KAKAOID(String s) {
this.s = s;
}
private KAKAOID replaceToLowerCase() {
s = s.toLowerCase();
return this;
}
private KAKAOID filter() {
s = s.replaceAll("[^a-z0-9._-]", "");
return this;
}
private KAKAOID toSingleDot() {
s = s.replaceAll("[.]{2,}", ".");
return this;
}
private KAKAOID noStartEndDot() {
s = s.replaceAll("^[.]|[.]$", "");
return this;
}
private KAKAOID noBlank() {
s = s.isEmpty() ? "a" : s;
return this;
}
private KAKAOID noGreaterThan16() {
if (s.length() >= 16) {
s = s.substring(0, 15);
}
s = s.replaceAll("[.]$", "");
return this;
}
private KAKAOID noLessThan2() {
StringBuilder sBuilder = new StringBuilder(s);
while (sBuilder.length() <= 2) {
sBuilder.append(sBuilder.charAt(sBuilder.length() - 1));
}
s = sBuilder.toString();
return this;
}
private String getResult() {
return s;
}
}
}
'프로그래머스 > LEVEL_1' 카테고리의 다른 글
프로그래머스 레벨1) 로또의 최고 순위와 최저 순위 (0) | 2021.09.03 |
---|
Comments