LeetCode 题解工作台
执行操作后的变量值
存在一种仅支持 4 种操作和 1 个变量 X 的编程语言: ++X 和 X++ 使变量 X 的值 加 1 --X 和 X-- 使变量 X 的值 减 1 最初, X 的值是 0 给你一个字符串数组 operations ,这是由操作组成的一个列表,返回执行所有操作后, X 的 最终值 。 示例 1: …
3
题型
8
代码语言
3
相关题
当前训练重点
简单 · 数组·string
答案摘要
我们遍历数组 ,对于每个操作 ,如果包含 `'+'`,那么答案加 ,否则答案减 。 时间复杂度 ,其中 为数组 的长度。空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·string 题型思路
题目描述
存在一种仅支持 4 种操作和 1 个变量 X 的编程语言:
++X和X++使变量X的值 加1--X和X--使变量X的值 减1
最初,X 的值是 0
给你一个字符串数组 operations ,这是由操作组成的一个列表,返回执行所有操作后, X 的 最终值 。
示例 1:
输入:operations = ["--X","X++","X++"] 输出:1 解释:操作按下述步骤执行: 最初,X = 0 --X:X 减 1 ,X = 0 - 1 = -1 X++:X 加 1 ,X = -1 + 1 = 0 X++:X 加 1 ,X = 0 + 1 = 1
示例 2:
输入:operations = ["++X","++X","X++"] 输出:3 解释:操作按下述步骤执行: 最初,X = 0 ++X:X 加 1 ,X = 0 + 1 = 1 ++X:X 加 1 ,X = 1 + 1 = 2 X++:X 加 1 ,X = 2 + 1 = 3
示例 3:
输入:operations = ["X++","++X","--X","X--"] 输出:0 解释:操作按下述步骤执行: 最初,X = 0 X++:X 加 1 ,X = 0 + 1 = 1 ++X:X 加 1 ,X = 1 + 1 = 2 --X:X 减 1 ,X = 2 - 1 = 1 X--:X 减 1 ,X = 1 - 1 = 0
提示:
1 <= operations.length <= 100operations[i]将会是"++X"、"X++"、"--X"或"X--"
解题思路
方法一:计数
我们遍历数组 ,对于每个操作 ,如果包含 '+',那么答案加 ,否则答案减 。
时间复杂度 ,其中 为数组 的长度。空间复杂度 。
class Solution:
def finalValueAfterOperations(self, operations: List[str]) -> int:
return sum(1 if s[1] == '+' else -1 for s in operations)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n) since we process each operation once. Space complexity is O(1) because we only maintain the variable X and no additional structures. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Check if candidates properly handle both pre- and post-increment forms equivalently.
- question_mark
Watch for solutions that overcomplicate with extra arrays or maps instead of simple counters.
- question_mark
Notice if they iterate multiple times unnecessarily rather than a single linear pass.
常见陷阱
外企场景- error
Miscounting X when confusing pre-increment (++X) and post-increment (X++) forms.
- error
Using extra data structures which are unnecessary and increase space complexity.
- error
Failing to process the operations in order, which can lead to incorrect final X.
进阶变体
外企场景- arrow_right_alt
Operations could include different variable names, requiring mapping from names to values.
- arrow_right_alt
Allowing multi-step operations like 'X+=2' or 'X-=3', extending the simulation approach.
- arrow_right_alt
Instead of returning final X, return an array of X after each operation for step-by-step tracking.