Question

write an algorithm function called balance() in javascript that takes in a string and returns a...

write an algorithm function called balance() in javascript that takes in a string and returns a strinf with balanced parantheses only. the string should be able to contain only parantheses, numbers, and letters. include comments of each portion of your code

balance(“()()”) should return “()()”
balance(“())”) should return “()”
balance(“a(b)c”) should return “a(b)c”
balance(“a(b)c())”) should return “a(b)c()”

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks

//required method

function balance(expression){

                //a string variable to store balanced expression

var updated="";

//number of opened parentheses

var opened=0;

//looping through the expression

for (var i = 0; i < expression.length; i++) {

    //getting current character

    var c=expression.charAt(i);

    //checking if it is an opening parentheses

    if(c=='('){

                //incrementing opened

                opened+=1;

      //adding c to updated

      updated+=c;

    }else if(c==')'){

      //closing parentheses found, checking if there is an

      //opening parentheses before

                if(opened>0){

                //only appending c to updated if there is an open parentheses before

                updated+=c;

        //decrementing number of opened parentheses

        opened-=1;

      }

    }else{

                //any other character, simply appending

                updated+=c;

    }

                }

//now if there is any unclosed parentheses, closing all

//or in other words, appending 'opened' number of parentheses

while(opened>0){

              //appending a ')'

              updated+=")";

    opened-=1;

}

return updated;

}

Add a comment
Know the answer?
Add Answer to:
write an algorithm function called balance() in javascript that takes in a string and returns a...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT