-
신규 아이디 추천코딩 테스트/Level 1 2021. 4. 4. 19:30반응형
신규 아이디 추천
2021 KAKAO BLIND RECRUITMENT
4526명 완료programmers.co.kr/learn/courses/30/lessons/72410
파이썬
정규표현식은 매번 쓰려면 리마인드가 안되서 간단하게...
def solution(new_id: str) -> str: new_id = new_id.lower() answer = '' for each in new_id: if each in 'abcdefghijklmnopqrstuvwxyz-_.1234567890': answer += each while '..' in answer: answer = answer.replace('..', '.') if len(answer) > 0 and answer[0] == '.': answer = answer[1:] if len(answer) > 0 and answer[-1] == '.': answer = answer[:-1] if len(answer) == 0: answer = 'a' if len(answer) >= 16: answer = answer[:15] if answer[-1] == '.': answer = answer[:-1] while len(answer) <= 2: answer += answer[-1] return answer
좀 더 정리한다면?
def solution(new_id: str) -> str: new_id = new_id.lower() answer = '' for each in new_id: if each in 'abcdefghijklmnopqrstuvwxyz-_.1234567890': answer += each while '..' in answer: answer = answer.replace('..', '.') if answer and answer[0] == '.': answer = answer[1:] if answer and answer[-1] == '.': answer = answer[:-1] if not answer: answer = 'a' if len(answer) >= 16: answer = answer[:15] if answer[-1] == '.': answer = answer[:-1] while len(answer) <= 2: answer += answer[-1] return answer
Java
자바에서 직접 문자열 처리하는 것 보다는
정규표현식이 편한 것 같습니다.class Solution { public String solution(String new_id) { new_id = new_id.toLowerCase(); new_id = new_id.replaceAll("[^\\w-._]+", ""); new_id = new_id.replaceAll("\\.+", "."); new_id = new_id.replaceAll("(^\\.)|(\\.$)", ""); if (new_id.length() == 0) new_id = "a"; if (new_id.length() >= 16) new_id = new_id.substring(0, 15); new_id = new_id.replaceAll("\\.$", ""); while (new_id.length() <= 2) new_id += new_id.charAt(new_id.length() - 1); return new_id; } }
반응형