leetcode balanced parentheses code example
Example 1: balanced parentheses leetcode
class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<Character>();
for(int i=0;i<s.length();i++)
{
char c=s.charAt(i);
if(c=='(' || c=='{' || c=='[')
{
stack.push(c);
}
else
{
if(stack.isEmpty()) return false;
char res=' ';
if(c==')')
{
res=stack.pop();
if(res!='(')
return false;
}
else if(c=='}')
{
res=stack.pop();
if(res!='{')
return false;
}
else
{
res=stack.pop();
if(res!='[')
return false;
}
}
}
if(stack.isEmpty()) return true;
return false;
}
}
Example 2: Algorithm check balanced parentheses
if (null == str || ((str.length() % 2) != 0)) {
return false;
} else {
char[] ch = str.toCharArray();
for (char c : ch) {
if (!(c == '{' || c == '[' || c == '(' || c == '}' || c == ']' || c == ')')) {
return false;
}
}
}