2011.执行操作后的变量值:简单题简单做

【LetMeFly】2011.执行操作后的变量值:简单题简单做

力扣题目链接:https://leetcode.cn/problems/final-value-of-variable-after-performing-operations/

存在一种仅支持 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--"

方法一:模拟

变量$X$的初始值是$0$,之后遍历$operations$中的每个$operation$,如果这个$operation$是$X++$或$++X$,则令$X$的值加一;否则令$X$的值减一。

小小小技巧: 其实不用真的把$operation$和$X++$进行比较,因为不管是$X++$还是$++X$,其第二个字符都是$+$

因此,我们只需要判断$operation$的第二个字符是否为$+$并进行响应的操作即可。

  • 时间复杂度$O(len(operations))$
  • 空间复杂度$O(1)$

AC代码

C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/*
* @LastEditTime: 2022-12-23 19:18:09
*/
// 下面代码中,ans即为题解中的X。使用变量ans是一些ACMer的习惯
class Solution {
public:
int finalValueAfterOperations(vector<string>& operations) {
int ans = 0;
for (auto& s : operations) {
if (s[1] == '+')
ans++;
else
ans--;
}
return ans;
}
};

C++

1
2
3
4
5
6
7
8
9
10
11
12
13
/*
* @LastEditTime: 2025-10-20 18:46:29
*/
class Solution {
public:
int finalValueAfterOperations(vector<string>& operations) {
int ans = 0;
for (string& op : operations) {
ans += op[1] == '+' ? 1 : -1;
}
return ans;
}
};

Go

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/*
* @LastEditTime: 2025-10-20 18:48:49
*/
package main

func finalValueAfterOperations(operations []string) (ans int) {
for _, op := range operations {
if op[1] == '+' {
ans++;
} else {
ans--
}
}
return
}

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/*
* @LastEditTime: 2025-10-20 18:48:23
*/
class Solution {
public int finalValueAfterOperations(String[] operations) {
int ans = 0;
for (String op : operations) {
if (op.charAt(1) == '+') {
ans++;
} else {
ans--;
}
}
return ans;
}
}

Python

1
2
3
4
5
6
7
8
'''
LastEditTime: 2025-10-20 18:47:35
'''
from typing import List

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

Rust

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/*
* @LastEditTime: 2025-10-20 18:56:38
*/
impl Solution {
pub fn final_value_after_operations(operations: Vec<String>) -> i32 {
let mut ans: i32 = 0;
for op in operations {
if op.as_bytes()[1] == b'+' {
ans += 1; // cannot write as: ans++;
} else {
ans -= 1;
}
}
ans
}
}

同步发文于CSDN,原创不易,转载请附上原文链接哦~
Tisfy:https://letmefly.blog.csdn.net/article/details/128423159


2011.执行操作后的变量值:简单题简单做
https://blog.letmefly.xyz/2022/12/23/LeetCode 2011.执行操作后的变量值/
作者
发布于
2022年12月23日
许可协议