📜  计算给定操作生成的数组的总和

📅  最后修改于: 2021-04-17 15:25:50             🧑  作者: Mango

给定一个由N个字符串组成的数组arr [] ,任务是查找遍历给定数组arr []时执行以下操作构成的brr []数组的总和(最初为空):

  • 如果数组arr []包含一个整数,则将该整数插入到数组brr []中
  • 如果数组arr []的字符串“ +” ,则将数组brr []中最后两个元素的和插入数组brr []中
  • 如果数组arr []的字符串“ D” ,则将值brr []的最后一个元素的两倍插入数组brr []
  • 如果数组arr []的字符串“ C” ,则将数组brr []的最后一个元素删除到数组brr []中

例子:

方法:解决给定问题的想法是使用堆栈。请按照以下步骤解决问题:

  • 初始化一个整数堆栈(例如S) ,并初始化一个变量(例如ans)0 ,以存储形成的数组的结果总和。
  • 遍历给定数组arr []并执行以下步骤:
    • 如果arr [i]的值为“ C” ,则从ans中减去堆栈的顶部元素,然后从S中弹出它。
    • 如果arr [i]的值为“ D” ,则在堆栈S中将堆栈S的顶部元素压入两次,然后将其值添加到ans
    • 如果arr [i]的值为“ +” ,则推入堆栈S的前两个元素之和的值,并将它们的和加到ans上
    • 否则,将arr [i]推入堆栈S ,并将其值添加到ans 
  • 循环之后,将ans的值打印为结果。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to find the sum of the array
// formed by performing given set of
// operations while traversing the array ops[]
void findTotalSum(vector& ops)
{
    // If the size of array is 0
    if (ops.empty()) {
        cout << 0;
        return;
    }
 
    stack pts;
 
    // Stores the required sum
    int ans = 0;
 
    // Traverse the array ops[]
    for (int i = 0; i < ops.size(); i++) {
 
        // If the character is C, remove
        // the top element from the stack
        if (ops[i] == "C") {
 
            ans -= pts.top();
            pts.pop();
        }
 
        // If the character is D, then push
        // 2 * top element into stack
        else if (ops[i] == "D") {
 
            pts.push(pts.top() * 2);
            ans += pts.top();
        }
 
        // If the character is +, add sum
        // of top two elements from the stack
        else if (ops[i] == "+") {
 
            int a = pts.top();
            pts.pop();
            int b = pts.top();
            pts.push(a);
            ans += (a + b);
            pts.push(a + b);
        }
 
        // Otherwise, push x
        // and add it to ans
        else {
            int n = stoi(ops[i]);
            ans += n;
            pts.push(n);
        }
    }
 
    // Print the resultant sum
    cout << ans;
}
 
// Driver Code
int main()
{
    vector arr = { "5", "-2", "C", "D", "+" };
    findTotalSum(arr);
 
    return 0;
}


Java
// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
class GFG
{
 
  // Function to find the sum of the array
  // formed by performing given set of
  // operations while traversing the array ops[]
  static void findTotalSum(String ops[])
  {
 
    // If the size of array is 0
    if (ops.length == 0)
    {
      System.out.println(0);
      return;
    }
 
    Stack pts = new Stack<>();
 
    // Stores the required sum
    int ans = 0;
 
    // Traverse the array ops[]
    for (int i = 0; i < ops.length; i++) {
 
      // If the character is C, remove
      // the top element from the stack
      if (ops[i] == "C") {
 
        ans -= pts.pop();
      }
 
      // If the character is D, then push
      // 2 * top element into stack
      else if (ops[i] == "D") {
 
        pts.push(pts.peek() * 2);
        ans += pts.peek();
      }
 
      // If the character is +, add sum
      // of top two elements from the stack
      else if (ops[i] == "+") {
 
        int a = pts.pop();
        int b = pts.peek();
        pts.push(a);
        ans += (a + b);
        pts.push(a + b);
      }
 
      // Otherwise, push x
      // and add it to ans
      else {
        int n = Integer.parseInt(ops[i]);
        ans += n;
        pts.push(n);
      }
    }
 
    // Print the resultant sum
    System.out.println(ans);
  }
 
  // Driver Code
  public static void main(String[] args)
  {
 
    String arr[] = { "5", "-2", "C", "D", "+" };
    findTotalSum(arr);
  }
}
 
// This code is contributed by Kingash.


Python3
# Python3 program for the above approach
 
# Function to find the sum of the array
# formed by performing given set of
# operations while traversing the array ops[]
def findTotalSum(ops):
 
    # If the size of array is 0
    if (len(ops) == 0):
        print(0)
        return
 
    pts = []
 
    # Stores the required sum
    ans = 0
 
    # Traverse the array ops[]
    for i in range(len(ops)):
 
        # If the character is C, remove
        # the top element from the stack
        if (ops[i] == "C"):
 
            ans -= pts[-1]
            pts.pop()
 
        # If the character is D, then push
        # 2 * top element into stack
        elif (ops[i] == "D"):
 
            pts.append(pts[-1] * 2)
            ans += pts[-1]
 
        # If the character is +, add sum
        # of top two elements from the stack
        elif (ops[i] == "+"):
 
            a = pts[-1]
            pts.pop()
            b = pts[-1]
            pts.append(a)
            ans += (a + b)
            pts.append(a + b)
 
        # Otherwise, push x
        # and add it to ans
        else:
            n = int(ops[i])
            ans += n
            pts.append(n)
 
    # Print the resultant sum
    print(ans)
 
# Driver Code
if __name__ == "__main__":
 
    arr = ["5", "-2", "C", "D", "+"]
    findTotalSum(arr)
 
    # This code is contributed by ukasp.


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to find the sum of the array
// formed by performing given set of
// operations while traversing the array ops[]
static void findTotalSum(string []ops)
{
 
    // If the size of array is 0
    if (ops.Length == 0)
    {
        Console.WriteLine(0);
        return;
    }
     
    Stack pts = new Stack();
     
    // Stores the required sum
    int ans = 0;
     
    // Traverse the array ops[]
    for(int i = 0; i < ops.Length; i++)
    {
         
        // If the character is C, remove
        // the top element from the stack
        if (ops[i] == "C")
        {
            ans -= pts.Pop();
        }
         
        // If the character is D, then push
        // 2 * top element into stack
        else if (ops[i] == "D")
        {
            pts.Push(pts.Peek() * 2);
            ans += pts.Peek();
        }
         
        // If the character is +, add sum
        // of top two elements from the stack
        else if (ops[i] == "+")
        {
            int a = pts.Pop();
            int b = pts.Peek();
            pts.Push(a);
            ans += (a + b);
            pts.Push(a + b);
        }
         
        // Otherwise, push x
        // and add it to ans
        else
        {
            int n = Int32.Parse(ops[i]);
            ans += n;
            pts.Push(n);
        }
    }
     
    // Print the resultant sum
    Console.WriteLine(ans);
}
 
// Driver Code
public static void Main()
{
    string []arr = { "5", "-2", "C", "D", "+" };
     
    findTotalSum(arr);
}
}
 
// This code is contributed by ipg2016107


输出:
30

时间复杂度: O(N)
辅助空间: O(N)