본문 바로가기
Problem Solving

[Swift] 프로그래머스 신규 아이디 추천(lv. 1)

by DuncanKim 2023. 2. 16.
728x90

[Swift] 프로그래머스 신규 아이디 추천(lv. 1)

 

1. 문제

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

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

2. 접근

주어진 대로 단계별 처리를 해주도록 필터나 맵을 써주면 되는 문제였다.

다만, 4, 5단계를 마치고 난 후 6, 7단계에서 특정 문자를 지웠는데, 마침표가 남아있어서 통과가 안 되었었다. 그래서 6, 7단계를 거치다가 마지막 문자가 마침표일 경우, 한 번 더 removeLast()를 해주는 것으로 보완을 하였다.

 

구현 문제였다.

 

 

3. 코드

import Foundation

func solution(_ new_id:String) -> String {
    // 1단계
    var id = new_id.map({ $0.isLetter ? Character($0.lowercased()) : $0 })
    
    // 2단계
    id = id.filter({ $0.isLetter || $0.isNumber || $0 == "-" || $0 == "_" || $0 == "." })
    
    // 3단계
    for (index, i) in id.enumerated() {
        if index < id.count - 1 && i == "." && id[index + 1] == "." {
            id[index] = "@"
        }
    }
    id = id.filter({ $0 != "@" })
    
    // 4단계, 5단계
    if id.first == "." {
        id.removeFirst()
    }
    if id.last == "." {
        id.removeLast()
    }
    if id.count == 0 {
        id.append("a")
    }
    
    // 6, 7단계
    if id.count > 15 {
        var temp = [Character]()
        for (index, i) in id.enumerated() {
            if index < 15 {
                temp.append(i)
            } else {
                break
            }
        }
        if temp.last == "." {
            temp.removeLast()
        }
        id = temp
    } else if id.count < 3 {
        let temp = id.last!
        while id.count != 3 {
            id.append(temp)
        }
    }
    return String(id)
}
728x90

댓글