Algorithm
本周选择的算法题是:Decode String。
规则
Given an encoded string, return its decoded string.
The encoding rule is: k[encoded_string]
, where the encoded_string
inside the square brackets is being repeated exactly k
times. Note that k
is guaranteed to be a positive integer.
You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc.
Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k
. For example, there won’t be input like 3a
or 2[4]
.
Example 1:
Input: s = "3[a]2[bc]"
Output: "aaabcbc"
Example 2:
Input: s = "3[a2[c]]"
Output: "accaccacc"
Example 3:
Input: s = "2[abc]3[cd]ef"
Output: "abcabccdcdcdef"
Example 4:
Input: s = "abc3[cd]xyz"
Output: "abccdcdcdxyz"
Constraints:
1 <= s.length <= 30
s
consists of lowercase English letters, digits, and square brackets'[]'
.s
is guaranteed to be a valid input.- All the integers in
s
are in the range[1, 300]
.
Solution
class Solution:
def decodeString(self, s: str) -> str:
ans, stack, num = "", [], 0
for char in s:
if char.isdigit():
num = num * 10 + int(char)
elif char == "[":
stack.append((num, ans))
num, ans = 0, ""
elif char == "]":
last_num, last_chars = stack.pop()
ans = last_chars + last_num * ans
else:
ans += char
return ans
Review
How to better manage business logic in your Flutter apps
通篇在讲 Monorepo 的优势,和 Flutter 没太大关系,不如改名为:如何用 Monorepo 更好地管理业务逻辑。
Advanced Python: 9 Best Practices to Apply When You Define Classes
这篇文章还不错,有作者独特的见解,比如作者在介绍 __str__
和 __repr__
之间的区别及使用场景时,并不像大多数文章那样,只是简单一句:__repr__
是给开发者看的,__str__
是给用户看的,实际上 __repr__
的字符串是可以通过 eval
重新构建对象的:
class Student:
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
def __repr__(self):
return f"Student({self.first_name!r}, {self.last_name!r})"
def __str__(self):
return f"Student: {self.first_name} {self.last_name}"
>>> student = Student("David", "Johnson")
>>> student
Student('David', 'Johnson')
>>> print(student)
Student: David Johnson
全文对得起 Best Practices 的说法。
Tip
通过 jekyll-feed 插件为博客添加了订阅功能,订阅地址。