-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path문자열 압축.swift
More file actions
80 lines (68 loc) · 2.14 KB
/
문자열 압축.swift
File metadata and controls
80 lines (68 loc) · 2.14 KB
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
//
// 문자열 압축.swift
//
//
// Created by chihoooon on 2022/01/11.
//
import Foundation
func solution(_ s:String) -> Int {
var answer: Int = 1001
if s.count == 1 {
return 1
}
for compressionWord in 1...s.count / 2 {
let index: String.Index
let remainder: String
if s.count % compressionWord == 0 {
index = s.index(s.startIndex, offsetBy: s.count)
remainder = ""
}
else {
let idx: Int = s.count / compressionWord
index = s.index(s.startIndex, offsetBy: compressionWord * idx)
remainder = s.substring(from: index)
}
let checkString = s.substring(to: index)
var compressedWord: String = ""
var x = 0
var splitString: [String] = []
while x < checkString.count / compressionWord {
let start = checkString.index(checkString.startIndex, offsetBy: x * compressionWord)
let end = checkString.index(start, offsetBy: compressionWord)
let range = start..<end
splitString.append(checkString.substring(with: range))
x += 1
}
x = 1
var compareString: String = splitString[0]
var cnt: Int = 1
while x < splitString.count {
if compareString == splitString[x] {
cnt += 1
splitString.remove(at: x)
}
else {
if cnt == 1 {
compressedWord += compareString
}
else {
compressedWord += String(cnt) + compareString
cnt = 1
}
compareString = splitString[x]
x += 1
}
}
if cnt == 1 {
compressedWord += compareString
}
else {
compressedWord += String(cnt) + compareString
}
compressedWord += remainder
if answer >= compressedWord.count {
answer = compressedWord.count
}
}
return answer
}