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
{
"()",
"()[]{}!",
"([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
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
Get step-by-step solutions from verified subject matter experts
