Joshua Chen Personal Blog

Back

📝 Note ✅ Ready · leetcode

Leetcode前置知识笔记

在B站学习的Leetcode的一些数据结构的基础概念和常用语法

views | comments

Leetcode 前置知识#

1. 集合(Set)#

所有的元素都是唯一的,底层基于哈希表。

#

"abc" in a  # -> True
python

#

a.add(1)    # -> {1, 1.5, "abc"}  (还是1,因为里面已经有了1)
a.add(2)    # -> {1, 2, 1.5, "abc"}
python

存东西时是无序的。

a.update([1])       # -> {1, 1.5, "abc"}
a.update([4, 5])    # -> {1, 2, 1.5, "abc", 4, 5}  (可以一次性加多个元素)
python

#

a.pop()             # 在 set 里是随机删一个,没太大意义
a.remove(2)         # -> {1, 1.5, ...}
python

常用函数#

len() / max() / min()

集合运算#

a = {1, 2, 3}
b = {2, 5, 9}
python
运算含义结果
a - ba 有但 b 没有的元素(差集){1, 3}
a | ba 有或 b 有(并集 A∪B){1, 2, 3, 5, 9}
a & ba 有并且 b 有(交集){2}
a ^ ba 和 b 不同时有的元素(对称差集){1, 3, 5, 9}

2. 字典(Dictionary)#

{"name": "Learning", "age": 18}
# key = value
python

#

dict["name"]      # -> "Learning"
dict["age"]       # -> 18
python

#

dict["platform"] = "YouTube"
python

#

dict["platform"] = "Bilibili"
python

#

dict.pop("platform")
dict.pop(k)       # 删除指定 key
python

遍历#

dict = {"name": "Stay with Learning", "age": 18}
python

判断 key 是否存在:

"name" in dict    # -> True
k in dict         # -> True / False
python

遍历所有 key:

for key in dict:
    print(key)
python

遍历所有 value:

for value in dict.values():
    print(value)
python

遍历 key-value 对:

for k, v in dict.items():
    print(k, v)
python

3. 字符串(String)#

s = "hello world"
# 由一个个 "h" "e" "l" ... 字符组成
python

索引与切片#

s[0]        # -> 'h'
s[-1]       # -> 'd'
s[:]        # -> "hello world"
s[0:4]      # -> "Hell"  (实际上只打印索引 0~3)
python

常用函数#

len()#

len(s)      # -> 11  (空格也算字符)
python

大小写判断#

s.upper()       # 全部变成大写并返回
s.isupper()     # 全是大写字母返回 True,否则返回 False
s.lower()       # 全部变成小写并返回
s.islower()     # 相反,判断是否全小写
s.swapcase()    # 大写变小写,小写变大写
python

数字判断#

s.isdigit()     # 全是数字返回 True
python

统计#

s.count("l")    # -> 3
python

去除空格#

s.strip()       # 去掉前后空格并返回
s.lstrip()      # 只去左边的空格
s.rstrip()      # 只去右边的空格
python

替换与分割#

s.replace("hello", "hi")    # -> "hi world"

s.split(" ")                # -> ["hello", "world"]
python

4. 树(Tree)#

待补充…

🗂️ This is a 📝 note in the knowledge base.

Content may be incomplete or work-in-progress.

← Back

Comment seems to stuck. Try to refresh?✨