跳转至

2011. 执行操作后的变量值

题目描述

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

解法

方法一:模拟

遍历数组 operations,对于每个操作 $operations[i]$,如果包含 '+',那么答案加 $1$,否则答案减 $1$。

时间复杂度为 $O(n)$,其中 $n$ 为数组 operations 的长度。空间复杂度 $O(1)$。

1
2
3
class Solution:
    def finalValueAfterOperations(self, operations: List[str]) -> int:
        return sum(1 if s[1] == '+' else -1 for s in operations)
1
2
3
4
5
6
7
8
9
class Solution {
    public int finalValueAfterOperations(String[] operations) {
        int ans = 0;
        for (var s : operations) {
            ans += (s.charAt(1) == '+' ? 1 : -1);
        }
        return ans;
    }
}
1
2
3
4
5
6
7
8
class Solution {
public:
    int finalValueAfterOperations(vector<string>& operations) {
        int ans = 0;
        for (auto& s : operations) ans += (s[1] == '+' ? 1 : -1);
        return ans;
    }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
func finalValueAfterOperations(operations []string) (ans int) {
    for _, s := range operations {
        if s[1] == '+' {
            ans += 1
        } else {
            ans -= 1
        }
    }
    return
}
1
2
3
4
5
6
7
function finalValueAfterOperations(operations: string[]): number {
    let ans = 0;
    for (let operation of operations) {
        ans += operation.includes('+') ? 1 : -1;
    }
    return ans;
}
1
2
3
4
5
6
7
8
9
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
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
/**
 * @param {string[]} operations
 * @return {number}
 */
var finalValueAfterOperations = function (operations) {
    let ans = 0;
    for (const s of operations) {
        ans += s[1] === '+' ? 1 : -1;
    }
    return ans;
};
1
2
3
4
5
6
7
int finalValueAfterOperations(char** operations, int operationsSize) {
    int ans = 0;
    for (int i = 0; i < operationsSize; i++) {
        ans += operations[i][1] == '+' ? 1 : -1;
    }
    return ans;
}

方法二

1
2
3
function finalValueAfterOperations(operations: string[]): number {
    return operations.reduce((r, v) => r + (v[1] === '+' ? 1 : -1), 0);
}

评论