存在一种仅支持 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--"
方法一:模拟
遍历数组 operations
,对于每个操作 '+'
,那么答案加
时间复杂度为 operations
的长度。
class Solution:
def finalValueAfterOperations(self, operations: List[str]) -> int:
return sum(1 if s[1] == '+' else -1 for s in operations)
class Solution {
public int finalValueAfterOperations(String[] operations) {
int ans = 0;
for (var s : operations) {
ans += (s.charAt(1) == '+' ? 1 : -1);
}
return ans;
}
}
class Solution {
public:
int finalValueAfterOperations(vector<string>& operations) {
int ans = 0;
for (auto& s : operations) ans += (s[1] == '+' ? 1 : -1);
return ans;
}
};
func finalValueAfterOperations(operations []string) (ans int) {
for _, s := range operations {
if s[1] == '+' {
ans += 1
} else {
ans -= 1
}
}
return
}
/**
* @param {string[]} operations
* @return {number}
*/
var finalValueAfterOperations = function (operations) {
let ans = 0;
for (const s of operations) {
ans += s[1] === '+' ? 1 : -1;
}
return ans;
};
function finalValueAfterOperations(operations: string[]): number {
let ans = 0;
for (let operation of operations) {
ans += operation.includes('+') ? 1 : -1;
}
return ans;
}
function finalValueAfterOperations(operations: string[]): number {
return operations.reduce((r, v) => r + (v[1] === '+' ? 1 : -1), 0);
}
impl Solution {
pub fn final_value_after_operations(operations: Vec<String>) -> i32 {
let mut ans = 0;
for s in operations.iter() {
ans += if s.as_bytes()[1] == b'+' { 1 } else { -1 };
}
ans
}
}
int finalValueAfterOperations(char **operations, int operationsSize) {
int ans = 0;
for (int i = 0; i < operationsSize; i++) {
ans += operations[i][1] == '+' ? 1 : -1;
}
return ans;
}