Algorithm/programmers

2021 Kakao blind - 신규 아이디 추천(문자열 파싱) javascript, Java 풀이

Ellery 2021. 9. 6. 00:56

https://programmers.co.kr/learn/courses/30/lessons/72410

 

코딩테스트 연습 - 신규 아이디 추천

카카오에 입사한 신입 개발자 네오는 "카카오계정개발팀"에 배치되어, 카카오 서비스에 가입하는 유저들의 아이디를 생성하는 업무를 담당하게 되었습니다. "네오"에게 주어진 첫 업무는 새로

programmers.co.kr

- 정규표현식을 안다면 굉장히 쉽게 풀 수 있는 문제이다. 만약 모른다면 시험시에 시간낭비가 크므로 정규표현식을 익히고 가는게 좋을 것 같다. 

조건 중에 알파벳 소문자, 숫자, '-'  '_'  '.'  만 아이디로 사용할 수 있다는 조건이 있는데 그중 소문자, 숫자, 언더바는 \w 표현식으로 검사할 수 있다. word 를 표현하며 알파벳, 숫자, _ 중의 한 문자임을 의미한다.

function solution(new_id) {
  let str = new_id
    .toLowerCase()
    .replace(/[^\w\-\.]/g, "")
    .replace(/\.+/g, ".")
    .replace(/^\.|\.$/g, "")
    .replace(/^$/g, "a")
    .slice(0, 15)
    .replace(/\.$/g, "");

  let lastchar = str[str.length - 1];
  while (str.length <= 2) {
    str += lastchar;
  }

  return str;
}
class Solution {
    public String solution(String new_id) {
        new_id = new_id
            .toLowerCase()
            .replaceAll("[^\\w\\-\\_\\.]", "")
            .replaceAll("\\.{2,}", ".")
            .replaceAll("^\\.|\\.$", "");

        if (new_id.isEmpty())
            new_id = "a";
        if (new_id.length() >= 16) {
            new_id = new_id.substring(0, 15).replaceAll("\\.$", "");
        }
        if (new_id.length() <= 2) {
            new_id += new_id.substring(new_id.length() - 1).repeat(3 - new_id.length());
        }

        return new_id;
    }
}

시간 날 때마다 틈틈히 이 사이트로 정규표현식 복습을 하고 있다

https://regexone.com/

 

RegexOne - Learn Regular Expressions - Lesson 1: An Introduction, and the ABCs

Regular expressions are extremely useful in extracting information from text such as code, log files, spreadsheets, or even documents. And while there is a lot of theory behind formal languages, the following lessons and examples will explore the more prac

regexone.com