Skip to content

Commit d986bad

Browse files
author
Partho Biswas
committed
157_Read_N_Characte_Given_Read4
1 parent effe0d6 commit d986bad

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -253,6 +253,7 @@ I have solved quite a number of problems from several topics. See the below tabl
253253
|42| [415. Add Strings](https://tinyurl.com/y7cbq62x) | [Python](https://tinyurl.com/wu6rdaw/415_Add_Strings.py), [Swift](https://tinyurl.com/wuja3c4/415_Add_Strings.swift) | [Art 1](https://tinyurl.com/y6v9uj9o) | Easy | --- |
254254
|43| **[65. Valid Number](https://tinyurl.com/yb6zsj3b)** | [Python](https://tinyurl.com/wu6rdaw/65_Valid_Number.py), [Swift](https://tinyurl.com/wuja3c4/65_Valid_Number.swift) | [Art 1](https://tinyurl.com/ycotov9v) | HARD | A fucking difficult but important problem. Chack DFA approach |
255255
|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 |
256+
|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 |
256257

257258

258259
</p>
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/**
2+
* The read4 API is defined in the parent class Reader4.
3+
* func read4(_ buf4: inout [Character]) -> Int;
4+
*/
5+
6+
// Appriach 1
7+
class Solution : Reader4 {
8+
/**
9+
* @param buf Destination buffer
10+
* @param n Number of characters to read
11+
* @return The number of actual characters read
12+
*/
13+
func read(_ buf: inout [Character], _ n: Int) -> Int {
14+
guard n > 0 else {
15+
return 0
16+
}
17+
var (copiedChars, readChars) = (0, 4)
18+
var buf4: [Character] = ["c", "a", "t", "!"]
19+
20+
while copiedChars < n && readChars == 4 {
21+
readChars = super.read4(&buf4)
22+
23+
for i in 0..<readChars {
24+
if copiedChars == n {
25+
return copiedChars
26+
}
27+
buf[copiedChars] = buf4[i]
28+
copiedChars += 1
29+
}
30+
}
31+
return copiedChars
32+
}
33+
}
34+

0 commit comments

Comments
 (0)