2011. 执行操作后的变量值:
存在一种仅支持 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 <= 100
- operations[i] 将会是 “++X”、“X++”、"–X" 或 “X–”
分析
- 一共有4种操作符号,但是只有2种操作。我们要把"++X"、“X++“当作加法, 把”–X” 或 "X–"当作减法。比较直观的方式就是直接上map,switch,if else,都可以。
- 每种操作符号都是三个字符,X可能在头或在尾,但是中间的字符却只有2种,正是’+‘和’-’。
题解
java
class Solution {
public int finalValueAfterOperations(String[] operations) {
int ans = 0;
for (String operation : operations) {
// 操作类型
char op = operation.charAt(1);
switch (op) {
case '+':
ans++;
break;
case '-':
ans--;
break;
}
}
return ans;
}
}
c
int finalValueAfterOperations(char \*\* operations, int operationsSize){
int ans = 0;
for (int i = 0; i < operationsSize; ++i) {
char op = operations[i][1];
switch (op) {
case '+':
++ans;
break;
case '-':
--ans;
break;
}
}
return ans;
}
c++
class Solution {
public:
int finalValueAfterOperations(vector<string>& operations) {
int ans = 0;
for (auto &operation : operations) {
char op = operation[1];
switch (op) {
case '+':
++ans;
break;
case '-':
--ans;
break;
}
}
return ans;
}
};
python
class Solution:
def finalValueAfterOperations(self, operations: List[str]) -> int:
ans = 0
for operation in operations:
if operation[1] == '+':
ans += 1
else:
ans -= 1
return ans
既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,涵盖了95%以上Go语言开发知识点,真正体系化!
由于文件比较多,这里只是将部分目录截图出来,全套包含大厂面经、学习笔记、源码讲义、实战项目、大纲路线、讲解视频,并且后续会持续更新