Skip to content

Commit de24afa

Browse files
committed
443_String_Compression
1 parent c0c08e6 commit de24afa

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -260,6 +260,7 @@ I have solved quite a number of problems from several topics. See the below tabl
260260
|44| **[791. Custom Sort String](https://tinyurl.com/yag8mcfd)** | [Python](https://tinyurl.com/wu6rdaw/791_Custom_Sort_String.py), [Swift](https://tinyurl.com/wuja3c4/791_Custom_Sort_String.swift) | --- | Medium | Loved this problem |
261261
|45| **[157. Read N Characters Given Read4](https://tinyurl.com/y5g49nqt)** | [Python](https://tinyurl.com/wu6rdaw/157_Read_N_Characte_Given_Read4.py), [Swift](https://tinyurl.com/wuja3c4/157_Read_N_Characte_Given_Read4.swift) | --- | Easy (Not So!) | Loved this problem |
262262
|46| **[722. Remove Comments](https://tinyurl.com/y288v3lv)** | [Python](https://tinyurl.com/wu6rdaw/722_Remove_Comments.py), [Swift](https://tinyurl.com/wuja3c4/722_Remove_Comments.swift) | [Art 1](https://tinyurl.com/y56j4p76) | Medium | |
263+
|47| **[443. String Compression](https://tinyurl.com/ybll48vn)** | [Python](https://tinyurl.com/wu6rdaw/443_String_Compression.py), [Swift](https://tinyurl.com/wuja3c4/443_String_Compression.swift) | [Art 1](https://tinyurl.com/y5knbkcd) | Medium | |
263264

264265

265266
</p>
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import Foundation
2+
class Solution {
3+
func compress(_ chars: inout [Character]) -> Int {
4+
guard chars.count > 0 else {
5+
return 0
6+
}
7+
8+
var (rPtr, wPtr) = (0, 0)
9+
while rPtr < chars.count {
10+
var (prevChar, frequency) = (chars[rPtr], 0)
11+
while rPtr < chars.count && prevChar == chars[rPtr] {
12+
frequency += 1
13+
rPtr += 1
14+
}
15+
chars[wPtr] = prevChar
16+
wPtr += 1
17+
if frequency > 1 {
18+
for num in Array(String(frequency)) {
19+
chars[wPtr] = num
20+
wPtr += 1
21+
}
22+
}
23+
}
24+
return wPtr
25+
}
26+
}

0 commit comments

Comments
 (0)