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

执行操作后的变量值【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), n n n为数组长度
      • 空间复杂度: O ( 1 ) O(1) O(1)

你可能感兴趣的:(每日一题,模拟,leetcode,动态规划,算法)