공대생의 비망록

[프로그래머스][Lv. 2] 문자열 압축 Swift 풀이 본문

Programming Language/Swift

[프로그래머스][Lv. 2] 문자열 압축 Swift 풀이

myungsup1250 2022. 4. 8. 15:09

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

 

코딩테스트 연습 - 문자열 압축

데이터 처리 전문가가 되고 싶은 "어피치"는 문자열을 압축하는 방법에 대해 공부를 하고 있습니다. 최근에 대량의 데이터 처리를 위한 간단한 비손실 압축 방법에 대해 공부를 하고 있는데, 문

programmers.co.kr

 

풀이는 추후에 차차 올리도록 하겠습니다...

 

2020 KAKAO BLIND RECRUITMENT 1차 코딩테스트에 나온 문제.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import Foundation
 
func solution(_ s:String-> Int {    
    var bestResult: Int = s.count
    for i in 1..<s.count / 2 + 1 {
        var slices: [String= [String]()
        var lastIndex: Int = -1
        for j in stride(from: 0, through: s.count - i, by: i) {
            slices.append(String(s[s.index(s.startIndex, offsetBy: j)...s.index(s.startIndex, offsetBy: j + i - 1)]))
            lastIndex = j + i
        }
        if s.count % i != 0 {
            slices.append(String(s[s.index(s.startIndex, offsetBy: lastIndex)...s.index(before: s.endIndex)]))
        }
        var record: String = "", result: String = ""
        var count: Int = 1
        for slice in slices {
            if record == slice {
                count += 1
            } else {
                if !record.isEmpty {
                    result += count > 1 ? "\(count)\(record)" : "\(record)"
                }
                record = slice
                count = 1
            }
        }
        if !record.isEmpty {
            result += count > 1 ? "\(count)\(record)" : "\(record)"
        }
        if bestResult > result.count {
            bestResult = result.count
        }
    }
    
    return bestResult
}
cs
Comments