问题描述
在一个神秘的实验室里,科学家小Z正在研究一种特殊的化学反应。她有一个名为 reactant 的初始物质,其起始值为 0。为了推动实验进展,小Z设计了一系列操作,这些操作可以改变 reactant 的浓度。
她的操作序列 instructions 包含以下两种指令:
++ 表示增加反应物的浓度,每次增加 1。
– 表示减少反应物的浓度,每次减少 1。
小Z希望你能帮助她计算在执行完所有操作后,反应物的最终浓度是多少。
约束条件:
时间限制:3s
数据范围为 1 ≤ instructions.size() ≤ 100,并且instructions[i] ∈{“++”,“−−”}
测试样例
样例1:
输入:instructions = [“++”, “–”, “++”]
输出:1
样例2:
输入:instructions = [“++”, “++”, “–”, “–”]
输出:0
样例3:
输入:instructions = [“++”, “++”, “–”]
输出:1
解题思路
这道题目综合运用了简单的字符串处理和基本的数学运算知识。
题目要求我们根据给定的操作序列 instructions 来计算反应物的最终浓度。每个操作要么是 ++,表示增加反应物的浓度 1,要么是 --,表示减少反应物的浓度 1。因此,我们可以将问题转化为对操作序列中的每个操作进行遍历,并根据操作的类型来更新反应物的浓度。最终,反应物的浓度就是所有操作对浓度的影响的总和。
- 初始化反应物浓度:首先,我们将反应物的初始浓度设为 0。
- 遍历操作序列:对于操作序列中的每一个操作,我们判断它是 ++ 还是 --。
- 如果操作是 ++,则将反应物的浓度增加 1。
- 如果操作是 --,则将反应物的浓度减少 1。
- 计算最终浓度:在遍历完所有操作后,反应物的最终浓度就是所有操作对浓度的影响的总和。
时间复杂度: 由于我们需要遍历整个操作序列,操作序列的长度为 n,因此时间复杂度为 O(n)。
空间复杂度: 我们只使用了常数级别的额外空间来存储反应物的浓度,因此空间复杂度为 O(1)。
代码
from typing import List
def solution(instructions: List[str]) -> int:
# 初始化 reactant 的值为 0
reactant = 0
# 遍历 instructions 列表
for instruction in instructions:
# 根据指令更新 reactant 的值
if instruction == "++":
# 增加 reactant 的值
reactant += 1
elif instruction == "--":
# 减少 reactant 的值
reactant -= 1
# 返回最终的 reactant 值
return reactant
if __name__ == '__main__':
print(solution(instructions=['++', '--', '++']))
print(solution(instructions=['++', '++', '--', '--']))
print(solution(instructions=['++', '++', '--']))
输出:
1
0
1
或者我们用列表表达式更简化答案:
def solution(instructions:list)->int:
return sum(1 if op[1] == '+' else -1 for op in instructions)
if __name__ == '__main__':
print(solution(instructions = ["++", "--", "++"]))
print(solution(instructions = ["++", "++", "--", "--"]))
print(solution(instructions = ["++", "++", "--"]))