LeetCode 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
1 <= operations.length <= 100
operations[i] 将会是 “++X”、“X++”、“–X” 或 “X–”
直接遍历即可:
class Solution {
public:
int finalValueAfterOperations(vector<string>& operations) {
int res = 0;
for (string &s : operations) {
if (s[1] == '+') {
++res;
} else if (s[1] == '-') {
--res;
}
}
return res;
}
};
如果输入数组operations的大小为n,此算法时间复杂度为O(n),空间复杂度为O(1)。