LeetCode 题解工作台

执行操作后的变量值

存在一种仅支持 4 种操作和 1 个变量 X 的编程语言: ++X 和 X++ 使变量 X 的值 加 1 --X 和 X-- 使变量 X 的值 减 1 最初, X 的值是 0 给你一个字符串数组 operations ,这是由操作组成的一个列表,返回执行所有操作后, X 的 最终值 。 示例 1: …

category

3

题型

code_blocks

8

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·string

bolt

答案摘要

我们遍历数组 ,对于每个操作 ,如果包含 `'+'`,那么答案加 ,否则答案减 。 时间复杂度 ,其中 为数组 的长度。空间复杂度 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·string 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

存在一种仅支持 4 种操作和 1 个变量 X 的编程语言:

  • ++XX++ 使变量 X 的值 1
  • --XX-- 使变量 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 <= 100
  • operations[i] 将会是 "++X""X++""--X""X--"
lightbulb

解题思路

方法一:计数

我们遍历数组 operations\textit{operations},对于每个操作 operations[i]\textit{operations}[i],如果包含 '+',那么答案加 11,否则答案减 11

时间复杂度 O(n)O(n),其中 nn 为数组 operations\textit{operations} 的长度。空间复杂度 O(1)O(1)

1
2
3
4
class Solution:
    def finalValueAfterOperations(self, operations: List[str]) -> int:
        return sum(1 if s[1] == '+' else -1 for s in operations)
speed

复杂度分析

指标
时间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
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

执行操作后的变量值题解:数组·string | LeetCode #2011 简单