Skip to content

Commit 5a83d03

Browse files
committed
encode and decode string
1 parent cef9dca commit 5a83d03

File tree

2 files changed

+56
-9
lines changed

2 files changed

+56
-9
lines changed

36.ValidSudoku.py

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -53,25 +53,24 @@
5353
# O(n ^ 2) time | O(n) space
5454
class Solution:
5555
def isValidSudoku(self, board: List[List[str]]) -> bool:
56-
row_set = defaultdict(set)
57-
col_set = defaultdict(set)
58-
sec_set = defaultdict(set)
56+
row_dict = defaultdict(set)
57+
col_dict = defaultdict(set)
58+
sec_dict = defaultdict(set)
5959

6060
for i in range(9):
6161
for j in range(9):
6262
num = board[i][j]
6363

64-
if num == '.':
64+
if num == ".":
6565
continue
6666

6767
sec = (i // 3, j // 3)
6868

69-
if num in row_set[i] or num in col_set[j] or num in sec_set[sec]:
69+
if num in row_dict[i] or num in col_dict[j] or num in sec_dict[sec]:
7070
return False
7171
else:
72-
row_set[i].add(num)
73-
col_set[j].add(num)
74-
sec_set[sec].add(num)
72+
row_dict[i].add(num)
73+
col_dict[j].add(num)
74+
sec_dict[sec].add(num)
7575

76-
print(row_set)
7776
return True

659.EncodeAndDecodeStrings.py

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
"""
2+
659. Encode and Decode Strings
3+
Medium
4+
5+
---
6+
Design an algorithm to encode a list of strings to a string.
7+
The encoded string is then sent over the network and is decoded back to the original list of strings.
8+
9+
Please implement encode and decode
10+
11+
12+
Example1
13+
Input: ["lint","code","love","you"]
14+
Output: ["lint","code","love","you"]
15+
Explanation:
16+
One possible encode method is: "lint:;code:;love:;you"
17+
18+
Example2
19+
Input: ["we", "say", ":", "yes"]
20+
Output: ["we", "say", ":", "yes"]
21+
Explanation:
22+
One possible encode method is: "we:;say:;:::;yes"
23+
"""
24+
25+
from typing import List
26+
27+
28+
class Solution:
29+
# O(n) time | O(1) space
30+
def encode(self, strs: List[str]):
31+
res = ""
32+
for s in strs:
33+
res += str(len(s)) + "#" + s
34+
return res
35+
36+
# O(n ^ 2) time | O(l) space
37+
def decode(self, str: str):
38+
res, i = [], 0
39+
40+
while i < len(str):
41+
j = i
42+
while str[j] != "#":
43+
j += 1
44+
l = int(str[i:j])
45+
res.append(str[j + 1 : j + 1 + l])
46+
i = j + 1 + l
47+
48+
return res

0 commit comments

Comments
 (0)