Parenthesis/Brackets Matching using Stack algorithm
Your code has some confusion in its handling of the '{' and '}' characters. It should be entirely parallel to how you handle '(' and ')'.
This code, modified slightly from yours, seems to work properly:
public static boolean isParenthesisMatch(String str) {
if (str.charAt(0) == '{')
return false;
Stack<Character> stack = new Stack<Character>();
char c;
for(int i=0; i < str.length(); i++) {
c = str.charAt(i);
if(c == '(')
stack.push(c);
else if(c == '{')
stack.push(c);
else if(c == ')')
if(stack.empty())
return false;
else if(stack.peek() == '(')
stack.pop();
else
return false;
else if(c == '}')
if(stack.empty())
return false;
else if(stack.peek() == '{')
stack.pop();
else
return false;
}
return stack.empty();
}
This code is easier to understand:
public static boolean CheckParentesis(String str)
{
if (str.isEmpty())
return true;
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < str.length(); i++)
{
char current = str.charAt(i);
if (current == '{' || current == '(' || current == '[')
{
stack.push(current);
}
if (current == '}' || current == ')' || current == ']')
{
if (stack.isEmpty())
return false;
char last = stack.peek();
if (current == '}' && last == '{' || current == ')' && last == '(' || current == ']' && last == '[')
stack.pop();
else
return false;
}
}
return stack.isEmpty();
}