티스토리 뷰

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

나의 풀이

import Foundation

func solution(_ new_id:String) -> String {
    
    var newID = new_id
    
    //#1
    newID = newID.lowercased()
    
    //#2
    var arr2: [String.Element] = []
    
    //"az09-_."
    Array(newID).forEach { c in
        
        if let value = c.asciiValue,
           value >= 97 && value <= 122
            || value >= 48 && value <= 57
            || value == 45
            || value == 95
            || value == 46 {
            
            arr2.append(c)
        }
    }
    
    //#3
    var arr3: [String.Element] = []
    for i in 0..<arr2.count {
        if i < arr2.count - 1, arr2[i] == ".", arr2[i+1] == "." {
            continue
        } else {
            arr3.append(arr2[i])
        }
    }

    //#4
    if arr3.first == "." {
        arr3.removeFirst()
    }
    
    if arr3.last == "." {
        arr3.removeLast()
    }
    
    //#5
    if arr3.count == 0 {
        arr3.append("a")
    }
    
    //#6
    var arr6: [String.Element] = []
    if arr3.count >= 16 {
        for i in 0..<15 {
            arr6.append(arr3[i])
        }
    } else {
        arr6 = arr3
    }
    
    if arr6.last == "." {
        arr6.removeLast()
    }
    
    //#7
    if arr6.count == 0 {
        return "aaa"
    } else if arr6.count == 1 {
        return "\(arr6[0])\(arr6[0])\(arr6[0])"
    } else if arr6.count == 2 {
        return "\(arr6[0])\(arr6[1])\(arr6[1])"
    } else {
        return String(arr6)
    }
}

 

다른 사람의 풀이

import Foundation

func solution(_ new_id:String) -> String {
    var myID: String = new_id

    //1차
    myID = myID.lowercased()

    //2차
    var newID: String = ""
    for i in myID {
        if i.isLetter || i.isNumber || i == "-" || i == "_" || i == "." {
            newID.append(i)
        }
    }

    //3차
    while newID.contains("..") {
        newID = newID.replacingOccurrences(of: "..", with: ".")
    }

    //4차
    while newID.hasPrefix(".") {
        newID.removeFirst()
    }

    while newID.hasSuffix(".") {
        newID.removeLast()
    }

    //5차
    if newID == "" {
        newID = "a"
    }

    //6차
    if newID.count >= 16 {
        let index = newID.index(newID.startIndex, offsetBy: 15)
        newID = String(newID[newID.startIndex..<index])
        if newID.hasSuffix(".") {
            newID.removeLast()
        }
    }

    //7차
    if newID.count <= 2 {
        while newID.count != 3 {
            newID = newID + String(newID.last!)
        }
    }

    return newID
}

배울 점

1. String에 isLetter, isNumber 등이 있음

2. while과 contains를 이용해서 중복문자를 제거

3. index(_: offsetBy:)로 주어진 인덱스로부터의 거리 계산

4. String(newID[newID.startIndex..<index])

 

댓글
공지사항