정규표현식으로 문제풀이를 하기위해서 좀 알아보았다.
문제에서 요구한 조건을 그대로 순서대로 구현한 필자의 코드이다.
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;
}
}
반응형
'코딩테스트 > Java' 카테고리의 다른 글
(2019카카오) 오픈채팅방 Java (0) | 2021.03.02 |
---|---|
(2021카카오) 프렌즈4블록 Java (0) | 2021.02.23 |
(2020카카오) 수식최대화 Java (0) | 2021.02.17 |
(2021카카오) 순위검색 Java (0) | 2021.02.11 |
(2021카카오) 메뉴 리뉴얼 Java (2) | 2021.02.09 |