【每日一题Day65】LC2011执行操作后的变量值 | 模拟
执行操作后的变量值【LC2011】
There is a programming language with only four operations and one variable
X
:
++X
andX++
increments the value of the variableX
by1
.--X
andX--
decrements the value of the variableX
by1
.Initially, the value of
X
is0
.Given an array of strings
operations
containing a list of operations, return the final value ofX
after performing all the operations.
再去练几道状态压缩dp!
-
思路:遍历整个数组,模拟加一和减一的操作,最后返回结果。进行加一或者减一的操作取决于字符串的第二个字符:
- 如果第二个字符是+号,那么执行加一操作
- 如果第二个字符是-号,那么执行减一操作
-
实现
class Solution { public int finalValueAfterOperations(String[] operations) { int res = 0; for (String operation : operations){ res += operation.charAt(1) == '+' ? 1 : -1; } return res; } }
- 复杂度
- 时间复杂度: O ( n ) O(n) O(n), n n n为数组长度
- 空间复杂度: O ( 1 ) O(1) O(1)
- 复杂度