执行操作后的变量值【LC2011】
There is a programming language with only four operations and one variable
X:
++XandX++increments the value of the variableXby1.--XandX--decrements the value of the variableXby1.Initially, the value of
Xis0.Given an array of strings
operationscontaining a list of operations, return the final value ofXafter 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),nnn为数组长度
- 空间复杂度:O(1)O(1)O(1)
- 复杂度

该博客探讨了一种只包含四种操作(++X, X++, --X, X--)的编程语言,初始变量X值为0。通过遍历并模拟数组中的操作字符串,计算X的最终值。时间复杂度为O(n),空间复杂度为O(1)。文章以一个具体的Java类实现为例,展示了如何根据字符串中的加减符号进行操作,并返回最终的X值。
1万+

被折叠的 条评论
为什么被折叠?



