Computer Science/자료구조

[6.30] 신규 아이디 추천 알고리즘 (47/100)

토마토. 2021. 6. 30. 18:42

1. 신규 아이디 추천

코딩테스트 연습 - 신규 아이디 추천 | 프로그래머스 (programmers.co.kr)

def solution(new_id):
    #소문자
    new_id = new_id.lower()
    new_id = list(new_id)
    allowed = ['-', '.', '_']
    i = 0
    #허용 문자 거르기
    while i < len(new_id):
      if new_id[i] in allowed or new_id[i].isalpha() or new_id[i].isdigit():
        i += 1
      else:
        del new_id[i]
    new_id = ''.join(new_id)
    #마침표 거르기
    while new_id.find('..') != -1:
      index = new_id.find('..')
      if index >= len(new_id)-2:
        new_id = new_id[:index] + new_id[index+1]
      else:
        new_id = new_id[:index] + new_id[index+1:]
    if new_id[0] == '.':
      new_id = new_id[1:]    
    if len(new_id) != 0 and new_id[-1] == '.':
      new_id = new_id[:-1]
    if len(new_id) == 0:
      new_id = 'a'
    if len(new_id) >= 16:
      new_id = new_id[:15]
      if new_id[-1] == '.':
        new_id = new_id[:-1]
    if len(new_id) <= 2:
      new_id = new_id + new_id[-1] * (3-len(new_id))
    

  
    return new_id

다른 사람 풀이 -> 파이썬도 공부해야햐ㅐ..

from re import sub

def solution(new_id):
    new_id = new_id.lower()
    new_id = sub("[^a-z0-9-_.]", "", new_id)
    new_id = sub("\.+", ".", new_id)
    new_id = sub("(^\.|\.$)", "", new_id)
    new_id = new_id if new_id else "a"
    new_id = sub("\.$", "", new_id[:15])
    new_id = new_id if len(new_id) > 3 else new_id + new_id[-1] * (3 - len(new_id))
    return new_id