【每日一题Day65】LC2011执行操作后的变量值 | 模拟

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

执行操作后的变量值【LC2011】

There is a programming language with only four operations and one variable X:

  • ++X and X++ increments the value of the variable X by 1.
  • --X and X-- decrements the value of the variable X by 1.

Initially, the value of X is 0.

Given an array of strings operations containing a list of operations, return the final value of X 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),nnn为数组长度
      • 空间复杂度:O(1)O(1)O(1)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值