-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCompression.swift
More file actions
39 lines (32 loc) · 1.01 KB
/
Compression.swift
File metadata and controls
39 lines (32 loc) · 1.01 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
/*
String Compression: Implement a method to perform basic string compression using the counts of repeated characters.
For example, the string aabcccccaaa would become a2b1c5a3.
If the compressed string would not become smaller that the original string, your method should return the original string.
You can assume the string has only uppercase and lowercase letters (a - z).
*/
func compress(_ str: String) -> String {
var result = ""
var counter = 0
var lastCharacter = Character("0")
for char in str {
if lastCharacter != char {
if counter > 0 {
result.append(lastCharacter)
result += "\(counter)"
}
lastCharacter = char
counter = 1
} else {
counter += 1
}
}
if counter > 0 {
result.append(lastCharacter)
result += "\(counter)"
}
if result.count > str.count {
result = str
}
return result
}
print(compress("aaabbcccggggg"))