make it shorter

hey , can someone make my code shorter and delete the parts that are not needed ??

thank you in advance



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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <iostream>
#include <stack>
#include <string>
using namespace std;

int main()
{
	stack<char> ms;
	string input;
	bool TF = true;
	int PC = 0;
	getline(cin,input);
	
	for (int i = 0; i < input.length(); i++)
	{
		if (input[i] == '(' || input[i] == '[' || input[i] == '{')
		{
			ms.push(input[i]);
			PC++;
		}
		else if (ms.empty() == false && input [i] == ')' && ms.top() == '('
		      || ms.empty() == false && input [i] == ']' && ms.top() == '['
		      || ms.empty() == false && input [i] == '}' && ms.top() == '{')
		{
			ms.pop();
			PC++;
		}
		else if (ms.empty() == true && input[i] == ')' || input[i] == ']' || input[i] == '}')
		{
			 TF = false; break;
		}
		else if (ms.empty() == false && input[i] == ')' || input[i] == ']' || input[i] == '}')
		{
			TF = false; break;
		}

	}
	if (TF == false)
	{
		cout << "\n Parentheses dont match \n";
		return 0;
	}
	if (ms.empty() == true && PC != 0)
	{
		cout << "\n Parentheses match \n";
	}
	if (PC == 0)
	{
		cout << "\n There was no parentheses \n";
	}
	else if (ms.empty() == false )
	{
		cout << "\n Stack is not empty\n ";
	}
}
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
37
38
39
40
41
42
43
44
#include <iostream>
#include <stack>
#include <string>
using namespace std;

int main()
{
    stack<char> ms;
    string input;
    bool match = true;
    int parens = 0;

    getline(cin, input);
    
    for (char c: input)
    {
        if (c == '(' || c == '[' || c == '{')
        {
            ms.push(c);
            ++parens;
        }
        else if (!ms.empty() && ((c == ')' && ms.top() == '(')
                             ||  (c == ']' && ms.top() == '[')
                             ||  (c == '}' && ms.top() == '{')))
        {
            ms.pop();
            ++parens;
        }
        else if (c == ')' || c == ']' || c == '}')
        {
             match = false;
             break;
        }
    }

    if (!match)
        cout << "\nParentheses dont match\n";
    else if (parens == 0)
        cout << "\nThere were no parentheses\n";
    else if (ms.empty())
        cout << "\nParentheses match\n";
    else
        cout << "\nStack is not empty\n";
}

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.

Range-based for loops, also known as For-each loops:
https://www.learncpp.com/cpp-tutorial/6-12a-for-each-loops/
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
THANK YOU ALL
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
Topic archived. No new replies allowed.