hey thank you for fast response
can u tell me how that for loop works ?
You may want to look up Ranged Based Loops. But basically it iterates through a container (a std::string in this case) one element at a time.
For a different take:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
|
#include <iostream>
#include <stack>
#include <string>
#include <map>
#include <cstring>
using namespace std;
const char* rparm = ")]}";
const map<char, char> brkts {{'(', rparm[0]}, {'[', rparm[1]}, {'{', rparm[2]}};
int main()
{
stack<map<char, char>::const_iterator> ms;
string input;
bool bad {};
getline(cin, input);
for (char c : input)
if (auto fd = brkts.find(c); fd != brkts.end())
ms.push(fd);
else
if (!ms.empty()) {
if (ms.top()->second == c)
ms.pop();
} else
if (strchr(rparm, c) != NULL) {
bad = true;
break;
}
if (!ms.empty() || bad)
cout << "\nParentheses don't match\n";
else
cout << "\nParentheses match\n";
}
|
Last edited on
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
|
#include <cassert>
char const* group(char const* s, char closer = '\0')
{
if (!s) return nullptr;
if (*s == ')' || *s == '}' || *s == ']' || *s == '\0')
return (closer == *s)? s: nullptr;
if (char inner = (*s == '(')? ')': (*s == '{')? '}': (*s == '[')? ']': '\0')
s = group(s + 1, inner);
return s? group(s + 1, closer): nullptr;
}
int main()
{
assert( group(R"()"));
assert( group(R"(())"));
assert( group(R"(((()([][{{abc}}]))))"));
assert( group(R"({[]})"));
assert( group(R"((abc))"));
assert(! group(R"((])"));
assert(! group(R"([{}]])"));
assert(! group(R"({}{)"));
assert( group(R"(()[])"));
assert( group(R"(()[]{}())"));
assert( group(R"((a)b[]{}()cd)"));
assert(! group(R"({)"));
assert( group(R"({ { [ ] } } )"));
assert(! group(R"({{{ })"));
assert(! group(R"(})"));
}
|
Last edited on
Sweet!
A bit of a problem is that it recurses on non-parens, so "{abcdefghijklmnopqrstuvwxyz}" goes 27 levels deep.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
|
#include <iostream>
#include <string>
#include <stack>
using namespace std;
bool check( const string &input, int &np )
{
const string LR = "([{)]}";
np = 0;
stack<int> stk;
for ( int p = input.find_first_of( LR ); p != string::npos; p = input.find_first_of( LR, p + 1 ) )
{
int q = LR.find( input[p] );
if ( q < 3 )
{
stk.push( q );
np++;
}
else if ( q < 6 )
{
if ( stk.empty() || q - 3 != stk.top() ) return false;
stk.pop();
}
}
return stk.empty();
}
int main()
{
int np;
string expr;
cout << "Enter an expression: "; getline( cin, expr );
if ( check( expr, np ) ) cout << "Matched with " << np << " pairs\n";
else cout << "Doesn't match";
}
|
Last edited on