What is your opinion of people deleting their questions after them being asked?
I only ask this because I know the purpose is to help EVERYONE but it has come to my attention that other people in my classes for example can see my code and use it without doing the work.
Line 87 iterates through the string once character at a time (c).
Line 91 checks to see if the current character is an opening brace. If it is, push it onto the stack.
Line 95: Current character is not an opening brace, check if the current character is a closing brace. Save the index of the matching brace within cl_brace in pos.
Line 97: Found a closing brace. If braces is empty, then not balanced. Note: This should be a returnfalse. There is no point in continuing.
Line 101: Check that the top of stack matches the indexed closing brace. If so, pop the stack.
Line 108: Didn't match the top character on the stack. This should also be a returnfalse.
Line 112: After processing the entire string, check if the stack is empty. If it's not empty, the braces were not balanced.
bool isBalanced( string s )
{
staticconst std::string op_braces = "({[" ; // Constant string type. Is used to verify whether parentheses have been opened in the text
staticconst std::string cl_braces = ")}]" ; // Constant string type. Is used to verify whether parentheses have been closed in the text
bool balance ; // Variable to return to the program, the result of the check performed. not initialized
stack<char> braces; // template ( container ) for char variables
for( auto c : s ) // for loop with c++14
{
auto pos = std::string::npos ; // variable pos initializated a 'npos'. npos = http://www.cplusplus.com/reference/string/string/npos/if ( op_braces.find( c ) != std::string::npos ) // If parenthesis was opened in string s then
{
braces.push( c ) ; // insert the value of 'c' ( type char = '(' , or '{' , or '[' ) on the container 'braces'
}
elseif ( (pos = cl_braces.find(c)) != std::string::npos ) // else if braces is closed ( pos != npos )
{
if ( braces.empty() ) // if braces.empty() is true ( empty() is one member fuction on stack ) and pos != npos ,
//then There is an unlocked or unlocked parenthesis
{
balance = false;
}
if ( braces.top() == op_braces[ pos ] ) // If the last value of 'c' is equal to element of op_braces on the position 'pos'
{
braces.pop(); // delete last input on the container 'braces' because the braces is balanced
}
else
{
balance = false; // otherwise it is missing a parenthesis, then is not balanced
}
}
}
if ( !braces.empty() ) // if the container is not empty, then the string is not balanced
{
balance = false ; // then the string is not balanced
}
else
{
balance = true ; // else yes
}
return balance;
}
I do not know if this is the best way to proceed, or even if the code works.
I hope to have helped you otherwise better specify your request