Blog Archive

Parenthesis Checker

 Parenthesis Checker

Given an expression string x. Examine whether the pairs and the orders of “{“,”}”,”(“,”)”,”[“,”]” are correct in exp.
For example, the function should return 'true' for exp = “[()]{}{[()()]()}” and 'false' for exp = “[(])”

Example 1:

Input:
{([])}
Output: 
true
Explanation: 
{ ( [ ] ) }. Same colored brackets can form 
balaced pairs, with 0 number of 
unbalanced bracket.

Example 2:

Input: 
()
Output: 
true
Explanation: 
(). Same bracket can form balanced pairs, 
and here only 1 type of bracket is 
present and in balanced way

Solution:

bool ispar(string x)
{
    // Your code here
    stack<char> s;
    for (int i = 0i < x.size(); i++)
    {
        if (x[i] == '(' || x[i] == '{' || x[i] == '[')
            s.push(x[i]);
        else
        {
            if (s.empty())
                return false;

            char c = s.top();
            if (x[i] == ')' && c != '(')
                return false;
            else if (x[i] == '}' && c != '{')
                return false;
            else if (x[i] == ']' && c != '[')
                return false;
            s.pop();
        }
    }
    return s.empty();
}

data structures and algorithms


1 comment:

  1. M88 Casino Hotel, Las Vegas - MapyRO
    Directions to M88 Casino Hotel, 동해 출장안마 Las Vegas (LAS VEGAS) 양산 출장샵 with 강원도 출장안마 MapyR 아산 출장안마 traffic updates and road conditions – from Las Vegas Boulevard to MGM National 군포 출장마사지 Harbor.

    ReplyDelete

Recent Post

Sort an array of 0s, 1s and 2s

  Sort an array of 0s, 1s and 2s- Data Structures   Sort an array of 0s, 1s and 2s- Data Structures Given an array of size N containing onl...