Question

In: Computer Science

Given a parentheses string s, compute the score of the string based on the following rule:...

Given a parentheses string s, compute the score of the string based on the following rule: • If s is not balanced, the score is 0. • () has score 1. • AB has score A + B, where A and B are balanced parentheses strings. • (A) has score 2 * A, where A is a balanced parentheses string. A balanced string satisfies the following requirements: • The number of ‘(’ equals the number of ‘)’ in the string. • Counting from the first position to any position in the string, the number of ‘(’ is greater than or equal to the number of ‘)’ in the string. (For example, ‘)(’ is not balanced.) The length of s is at most 30. Input: The input is a parentheses string s. Output: Print the score of s. Examples:

1. Input: (())

Output: 2

2. Input: (()(()))

Output: 6

3. Input: ((()())

Output: 0

sketch code:

#include <iostream>

#include <string>

using namespace std;

void SolveC(){

string s;

cin >> s;

/* your code starts here */

}

int main() {

SolveC();

return 0;

}

Solutions

Expert Solution

The solution to the above problem in c++11 is as follows:-

Code-

#include <iostream>
#include <string>
#include <stack>
using namespace std;

void SolveC(){
   string s;
   cin >> s;
   /* your code starts here */
   int finalscore = 0; //calculate final score
   stack <int> st;//Stack to store scores
   for(int i = 0; i < s.length(); i++){
      
       if(s[i] == '('){
           st.push(-1); //Push -1 into the stack for just open parenthesis
       }else{
           if(st.top() == -1){
               st.pop();
               st.push(1); //push score of single () into the stack
           }else{
               int score=0;
               //Calculate score of substring
               while(st.top()!=-1){
                   score+=st.top();
                   st.pop();
                   if(st.empty()){ //Print 0 in case of unbalanced paranthesis
                       cout<<"0\n";
                       return;
                   }
               }
               score=2*score;              
               st.pop();
               st.push(score);
           }
       }
   }
   //Calculate final scores
   while(!st.empty()){
       if(st.top()==-1){ //Print 0 in case of unbalanced paranthesis
           cout<<"0\n";
           return;
       }
       finalscore += st.top();
       st.pop();
   }
   cout<<finalscore<<"\n";
}

int main() {
SolveC();
return 0;
}

Code Screenshots-

Outputs-

Feel free to comment for any issues, do rate the answer positively


Related Solutions

Python: If I am given a string consisting only of parentheses - (, ), {, },...
Python: If I am given a string consisting only of parentheses - (, ), {, }, [, and ], how would I write a Boolean function that takes a string and decides if it consists of valid nested parenthesis? One of the hints given was to use stack. For example --> {()[{}]}' is valid.
Write a method called isMatch that takes a string of parentheses and check if all parentheses...
Write a method called isMatch that takes a string of parentheses and check if all parentheses match correctly. The parameter string might consist of other characters. Ignore other characters, just check the () {} [] public static boolean isMatch(String expressionLine); Use a JCF ArrayDeque or LinkedList as a stack to store all open or left parentheses. Use following main method to check your method. public static void main(String[] args) { String[] expression = new String[]{"{5*(x+2)+(y-1);}", "32*(20+(x[i]*3)-1", "((){([][])})", "({}((0))", "{([]})", "{}())",...
Rule Based System 1. Given the rule following rules from the class notes on production rules...
Rule Based System 1. Given the rule following rules from the class notes on production rules to convert an Arabic number less than 40 to a roman numeral. USING LOGIC Rule 1: if x is null then prompt the user and read x Rule 2: if x is higher than 999 then print “too Big” and make x null Rule 3: if x is between 10 and 39 then print “X” and reduce x by 10 Rule 4: if x...
Use the product rule or quotient rule, as appropriate, to compute each of the following derivatives:...
Use the product rule or quotient rule, as appropriate, to compute each of the following derivatives: A. sin^2(x) B. sin(x) cos(x) C. sec(x) tan(x) D. x^2ln(x) E. xtan(x)
Project: Given a string s and an integer array indices of the same length. The string...
Project: Given a string s and an integer array indices of the same length. The string s will be shuffled such that the character at the i th position moves to indices[i] in the shuffled string. Return the shuffled string. Example: Input: s = "codeleet", indices = [4,5,6,7,0,2,1,3] Output: "leetcode" Explanation: As shown, "codeleet" becomes "leetcode" after shuffling. You need to do: Create a class called ShuffledStringApp. Keeping class StringOperation and IO in util package. In this project, you will...
Given Codd's Rule 4: Rule 4: Dynamic online catalog based on the relational model: The database...
Given Codd's Rule 4: Rule 4: Dynamic online catalog based on the relational model: The database description is represented at the logical level in the same way as ordinary data, so that authorized users can apply the same relational language to its interrogation as they apply to the regular data. In three sentences, explain what this means. Give two example queries from MySQL that show how MySQL realizes the concepts
public static java.lang.String removerec(java.lang.String s) Returns a string similar to the given string with all runs...
public static java.lang.String removerec(java.lang.String s) Returns a string similar to the given string with all runs of consecutive, repeated characters removed. For example, given "apple", returns "aple" given "banana", returns "banana" given "baaannannnnaa", returns "banana" given an empty string, returns an empty string Parameters: s - given string Returns: string created from s by removing runs of the same character
Given their performance record and based on empirical rule what would be the upper bound of...
Given their performance record and based on empirical rule what would be the upper bound of the range of sales values that contains 68% of the monthly sales? Monthly Sales 7612.98 8393.66 7780.23 7091.18 9450.62 8220.44 7339.97 8589.48 7621.12 8067.21 7432.08 7621.69 7256.68 7821.21 8074.25 8173.28 7745.28 7398.05 7098.52 8484.65 7987.16 7041.5 7937.03 8508.25 8145.68 7802.15 8482.05 6171.19 8870.03 7906.6 9093.87 8010.37 6971.06 8800.08 7209.09 8852.65 8319.31 7982.86 8405.35 9166.74 7634.14 8315.4 8680.97 7540.09 9461.91 9414.57 9335.68 8638.78 7285.7 8376.95...
Given the following regression equation with dependent variable is NHL player salaries (with t-statistics in parentheses:...
Given the following regression equation with dependent variable is NHL player salaries (with t-statistics in parentheses: Salary = 566,400 + 71,928 Goals + 20,403 Assists + 98,430 All-Star (3.45) (2.96) (3.5) (1.30) R2 = 0.95 where: Salary= NHL Salary in $ Goals= Number of career goals Assists = Number of career assists All-Star =1 if All-Star in the previous season, 0 otherwise. A. Interpret the R2. B. Interpret the each of the coefficient—What do they mean (do they make sense?)...
In java please Question: You are given a string s. Your task is to count the...
In java please Question: You are given a string s. Your task is to count the number of ways of splitting s into three non-empty parts a, b and c (s = a + b + c) in such a way that a + b, b + c and c + a are all different strings. For s = "xzxzx", the output should be countWaysToSplit(s) = 5. Consider all the ways to split s into three non-empty parts:
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT