본문 바로가기
Swift

Swift 코딩 테스트 준비 - Java to Swift 😱

by HaningYa 2020. 7. 1.
728x90

 

이번에 하계 인턴을 위한 코테를 칠 예정이다.

오늘 안내 메일을 받았는데 세상에나 Swift 언어만 지원한다고 한다.

iOS직군이라 그런것 같으나 언어 제한을 둘 줄은 몰랐다.

평소에 Swift로 슬슬 풀어볼까 생각이 들었었는데 

이 참에 Swift로 풀어야 겠다. 🤦‍♂️

 

문자열 - 가운데 수 찾기

func solution(_ s:String) -> String {
    if(s.count%2==0){
        let index1 = s.index(s.startIndex, offsetBy: s.count/2-1)
        let index2 = s.index(s.startIndex, offsetBy: s.count/2)
        return "\(s[index1])\(s[index2])"
    }else{
        let index1 = s.index(s.startIndex, offsetBy: s.count/2)
        return "\(s[index1])"
   
    }    
}

Set - 숫자외 포함 유무

func solution(_ s:String) -> Bool {
    // 변수 뒤에 : Set 이라 명시 안하면 배열로 인식한다.
    var numSet : Set = ["1","2","3","4","5","6","7","8","9","0"]

    if s.count != 4 || s.count == 6{
        return false
    }
    
    for i in 0..<s.count{
        let index = s.index(s.startIndex, offsetBy: i)
        if numSet.contains("\(s[index])") == false {
            return false
        }
    }
    return true
}

String -> Int 변환 시

var str = "a1234"
print( Int(str) ) // return nil

var str = "1234"
print( Int(str) ) // return 1234

String 배열에서 특정 문자열을 찾고 싶을 때

func solution(_ seoul:[String]) -> String {
    return "김서방은 \(seoul.firstIndex(of: "Kim")!)에 있다"
}

문자열 에서 첫글자 없앨 때

func solution(_ s:String) -> Int {
    var answer = 0
    if s[s.startIndex] == "-" {
        let tmp = s.dropFirst()
        answer = Int(tmp)!*(-1)
    }else{
        answer = Int(s) ?? 0
    }
    return answer
}

문자열 정렬 && 문자열 첫글자 없애기

func solution(_ strings:[String], _ n:Int) -> [String] {
    var strArray = strings;
    for i in 0..<strings.count{
        let index = strings[i].index(strings[i].startIndex, offsetBy: n)
        strArray[i] = "\(strings[i][index])"+strings[i]
    }
    strArray.sort()
    for i in 0..<strArray.count{
        strArray[i] = String(strArray[i].dropFirst())
    }
    return strArray
}

for loop 반대로 iterate

for i in (1...10).reversed() {
    print(i) // prints 10 through 1
}

struct는 아닌데 몇 가지 변수 포함하는 배열과 정렬

var queue : [(Int,Int,String)] = []
queue.append((1,13,"test"))
queue.append((3,113,"advb"))
queue.append((2,123,"qwewq"))
print(queue[0].2)

print(queue)
queue.sort { $0.2 < $1.2 }
print(queue)

Dictionary

import Foundation

func solution(_ clothes:[[String]]) -> Int {
    var answer = 1;
    var dic : [String:Int] = [:]
    for i in 0..<clothes.count {
        let category = clothes[i][1]
        if dic.keys.contains(category) {
            dic[category] = dic[category]! + 1
        }else{
            dic[category] = 1
        }
    }
    print(dic)
    for (key, value) in dic {
        answer = answer * (value+1)
    }
    answer = answer - 1
    return answer
}

소숫점 올림 반올림

  var angle : Double = Double(h)/Double(w)
    
    let height = Int64(angle.rounded(.up))
    
//case awayFromZero
//case down
//case toNearestOrAwayFromZero
//case toNearestOrEven
//case towardZero
//case up
 

[Swift] 알고리즘에 필요한 Swift Basic 총정리

Swift로 알고리즘 초초초초보부터 시작해서 정리한 문법들 올립니다

medium.com

 

 

 

콜렉션 타입 (Collection Types)

 

jusung.gitbook.io

 

Swift.org

Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

swift.org

 

 

[알고리즘][Swift] #1. 프린터

안녕하세요! caution 입니다. '-' 알고리즘 문제 풀이 첫 포스팅이네요! 요새 한 주에 한 두 개씩 알고리즘 문제를 풀어보고 있어요. 알고리즘의 알자도 몰라서 일주일에 두 개 푸는 게 한계입니다!

caution-dev.tistory.com

 

728x90

'Swift' 카테고리의 다른 글

Swift 알고리즘에 쓰이는 문법 정리  (0) 2020.07.07
Swift String to Array (component)  (0) 2020.07.03
[🗂 Swift Data Structure] - Stack  (0) 2020.06.25
스위프트 101 - Objects and Classes  (0) 2020.03.26
스위프트 101 - 소개  (0) 2020.03.25

댓글