Skip to content

Commit e0238c7

Browse files
committed
717.1-bit and 2-bit Characters.
1 parent 0c231cb commit e0238c7

File tree

4 files changed

+56
-0
lines changed

4 files changed

+56
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/**
2+
We have two special characters:
3+
4+
- The first character can be represented by one bit 0.
5+
- The second character can be represented by two bits (10 or 11).
6+
Given a binary array bits that ends with 0, return true if the last character must be a one-bit character.
7+
8+
9+
10+
Example 1:
11+
Input: bits = [1,0,0]
12+
Output: true
13+
Explanation: The only way to decode it is two-bit character and one-bit character.
14+
So the last character is one-bit character.
15+
16+
Example 2:
17+
Input: bits = [1,1,1,0]
18+
Output: false
19+
Explanation: The only way to decode it is two-bit character and two-bit character.
20+
So the last character is not one-bit character.
21+
22+
23+
Constraints:
24+
- 1 <= bits.length <= 1000
25+
- bits[i] is either 0 or 1.
26+
*/
27+
class Solution {
28+
func isOneBitCharacter(_ bits: [Int]) -> Bool {
29+
var result = [Int]()
30+
for (i, c) in bits.enumerated() {
31+
if c == 0 && i != bits.count - 1 {
32+
result.removeAll()
33+
} else {
34+
result.append(c)
35+
}
36+
}
37+
if result.last != 0 { return false }
38+
return (result.count - 1) % 2 == 0
39+
}
40+
}
41+
42+
let s = Solution()
43+
let r = s.isOneBitCharacter([1, 1, 0, 1, 1, 1, 0, 1, 1, 0])
44+
print(r)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2+
<playground version='5.0' target-platform='ios' buildActiveScheme='true' importAppTypes='true'>
3+
<timeline fileName='timeline.xctimeline'/>
4+
</playground>

Easy/717.1-bit and 2-bit Characters.playground/playground.xcworkspace/contents.xcworkspacedata

+7
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,7 @@
129129
125. [Long Pressed Name](https://github.com/recherst/leetcode-algtorithm/blob/main/Easy/925.Long%20Pressed%20Name.playground/Contents.swift)
130130
126. [Binary Search](https://github.com/recherst/leetcode-algtorithm/blob/main/Easy/704.Binary%20Search.playground/Contents.swift)
131131
127. [To Lower Case](https://github.com/recherst/leetcode-algtorithm/blob/main/Easy/709.To%20Lower%20Case.playground/Contents.swift)
132+
128. [1-bit and 2-bit Characters](https://github.com/recherst/leetcode-algtorithm/blob/main/Easy/717.1-bit%20and%202-bit%20Characters.playground/Contents.swift)
132133

133134
#### Medium
134135

0 commit comments

Comments
 (0)