LeetCode(String) 2011. Final Value of Variable After Performing Operations

1.问题

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.

Example 1:

Input: operations = [“–X”,“X++”,“X++”]
Output: 1
Explanation: The operations are performed as follows:
Initially, X = 0.
–X: X is decremented by 1, X = 0 - 1 = -1.
X++: X is incremented by 1, X = -1 + 1 = 0.
X++: X is incremented by 1, X = 0 + 1 = 1.

Example 2:

Input: operations = [“++X”,“++X”,“X++”]
Output: 3
Explanation: The operations are performed as follows:
Initially, X = 0.
++X: X is incremented by 1, X = 0 + 1 = 1.
++X: X is incremented by 1, X = 1 + 1 = 2.
X++: X is incremented by 1, X = 2 + 1 = 3.

Example 3:

Input: operations = [“X++”,“++X”,“–X”,“X–”]
Output: 0
Explanation: The operations are performed as follows:
Initially, X = 0.
X++: X is incremented by 1, X = 0 + 1 = 1.
++X: X is incremented by 1, X = 1 + 1 = 2.
–X: X is decremented by 1, X = 2 - 1 = 1.
X–: X is decremented by 1, X = 1 - 1 = 0.

2.解决思路

方法1:

1.判断数据是存在,不存在返回0
2.设置一个int[]temp数组,长度和String[] operations的长度相同
3.将String[] operations的元素遍历,进行判断并赋值为整数的值放入temp数组中
4.遍历int[]temp的元素进行求和

方法2:

1.定义一个变量res,初始值为0
2.遍历String[] operations,用contains() Method如果元素包含“+”,在res上加一,否则减-
3.返回res值

3.代码实现

代码1:

class Solution {
    public int finalValueAfterOperations(String[] operations) {
    //1.判断数据是存在,不存在返回0
        if(operations == null){
                return 0;
         }
    //2.设置一个int[]temp数组,长度和String[] operations的长度相同
        int[] temp = new int[operations.length]; 
    //3.将String[] operations的元素遍历,进行判断并赋值为整数的值放入temp数组中
        for(int i=0;i<operations.length;i++){
            if(operations[i].equals("X++") || operations[i].equals("++X")){
                temp[i] = 1;
            }else{
                temp[i] = -1;

            }
        }
	//4.遍历int[]temp的元素进行求和
        int sum=0;
        for(int j=0;j<temp.length;j++){
            sum += temp[j];
        }
        return sum;       
    }
}

代码2

class Solution {
    public int finalValueAfterOperations(String[] operations) {
        //1.定义一个变量res,初始值为0
        int res = 0;
        //2.遍历String[] operations,用contains() Method如果元素包含“+”,在res上加一,否则减-
        for(int i = 0; i < operations.length; i++){
            if(operations[i].contains("+"))
                res++;
            else
                res--;
        }
        //3.返回res值
        return res;     
    }
}

你可能感兴趣的:(#,Leecode,leetcode,算法,数据结构)