Adobe Interview Question
Software Engineer / Developersint matchParenthesis (char str[], int len) {
int i = 0 ;
stack<char> s ;
for ( ; i < len ; i ++ ) {
if ( str[i] == '(' || str[i] == '{' || str[i] == '[' )
s.push (str[i]) ;
else {
switch (str[i]) {
case ')' : if ( s.top() != '(' )
return 0 ;
s.pop () ;
break ;
case '}' : if ( s.top() != '{' )
return 0 ;
s.pop () ;
break ;
case ']' : if ( s.top() != '[' )
return 0 ;
s.pop () ;
break ;
}
}
}
return (s.empty() ? 1 : 0) ;
}
public static void paranthesis() {
String str = "{}{{}}{}}";
int i = 0,count=0;
while(i<str.length()){
char c1 = str.charAt(i++);
if(c1=='{')
count = count +1;
else
count = count -1;
if(count<0){
System.out.println("noo! ");
break;
}
}
if(count>0)
System.out.println("noo ");
else if(count==0)
System.out.println("yes ");
}
The above solution is wrong! It returns true even on input "}}{{".
For correct solution, a stack must be used.
bool paranthesis(char str[])
{
int i=0, count = 0;
for(i=0; i < strlen(str); i++)
{
if(str[i] == '}')
count++;
else if(str[i] == '{')
{
count--;
if(count == -1)
{
printf("Paranthesis don't match")
exit(0);
}
}
}
}
Sorry for the bool return type, it can be made void.
This code shall print No if the starting paranthesis is '}' in the string.
Example "}}{{"
I am sorry Rahul but above solution is incorrect because it doesn't take care of the fact that an opening parenthesis should come before its corresponding closing parenthesis.
In parenthesis matching, parenthesis must open before closing just like any valid mathematical expression.
Correct examples:
1. ((()))
2. () () ()
3. (()) ()
Incorrect :
1. ((( ))))
Incorrect because no. of opening parenthesis is not equal to no. of closing parenthesis.
2. )(
Incorrect because closing parenthesis comes before corresponding opening parenthesis.
Let us start by understanding the problem.
Here are a few examples:
As you can see, the number of open and closed parens being equal does not guarantee that the parens are matching. Their order is important too.
We take care of this order using a stack.
An algorithm that checks whether the matching in a given text is correct is as follows:
- Mayank Jaiswal January 17, 2012