Skip to content

Commit 6543850

Browse files
committed
counting-bits, encode-and-decode-strings solved
1 parent e29c515 commit 6543850

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

counting-bits/sun912.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
"""
2+
3+
"""
4+
5+
6+
class Solution:
7+
def countBits(self, n: int) -> List[int]:
8+
dp = [0] * (n+1)
9+
offset = 1
10+
11+
for i in range(1, n+1):
12+
if offset * 2 == i:
13+
offset = i
14+
dp[i] = 1 + dp[i-offset]
15+
return dp
16+
17+
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
"""
2+
TC: O(n)
3+
4+
"""
5+
class Solution:
6+
"""
7+
@param: strs: a list of strings
8+
@return: encodes a list of strings to a single string.
9+
"""
10+
def encode(self, strs):
11+
result = ""
12+
for str in strs:
13+
result += str(len(str)) + "#" + str
14+
return result
15+
16+
"""
17+
@param: str: A string
18+
@return: decodes a single string to a list of strings
19+
"""
20+
def decode(self, str):
21+
result = []
22+
idx = 0
23+
while idx < len(str):
24+
temp_idx = idx
25+
while str[temp_idx] != "#":
26+
temp_idx += 1
27+
length = int(str[idx:temp_idx])
28+
result.append(str[temp_idx+1:temp_idx+length+1])
29+
idx = temp_idx + length + 1
30+
return result

0 commit comments

Comments
 (0)