Question: Please answer in C++ Programming Language! I'm not sure what I'm doing wrong... most test cases pass but some don't Question: Complete the function isValid

Please answer in C++ Programming Language!

I'm not sure what I'm doing wrong... most test cases pass but some don't

Question:

Complete the function isValid that checks if a string has valid brackets.

The function isValid takes a string as input, which may contain three kinds of brackets: '(', ')', '{', '}', '[', ']'. A valid input should not contain any unmatched, extra or hanging brackets of any kind. And they must close in the correct order. Your function should ignore any characters other than these three types of brackets.

Example

"()[]{}!" // valid "([123)]" // invalid

main.cpp:

#include

#include

using namespace std;

#include "isValid.cpp"

int main() {

vector tests =

{

"()",

"()[]{}!",

"([cs225)]",

"abc([])",

"{",

"[]]",

""

// add tests here!

};

cout << std::boolalpha << endl;

for (string& t : tests) {

cout << t << " : ";

cout << isValid(t);

cout << endl << endl;

}

}

isValid.cpp:

#include

#include

#include

using namespace std;

bool isValid(string input) {

stack st;

char c;

for (unsigned long i = 0; i < input.size(); i++) {

if (input[i] != '(' && input[i] != ')' && input[i] != '{' && input[i] != '}' && input[i] != '[' && input[i] != ']') {

continue;

}

if (input[i] == '(' || input[i] == '[' || input[i] == '{') {

st.push(input[i]);

continue;

}

if (st.empty()) { return false; }

switch(input[i]) {

case ')':

c = st.top();

st.pop();

if (c == '[' || c == '{') { return false; }

break;

case '}':

c = st.top();

st.pop();

if (c == '(' || c == '[') { return false; }

break;

case ']':

c = st.top();

st.pop();

if (c == '[' || c == '{') { return false; }

break;

}

return true;

}

return st.empty();

}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!