Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.
Subscribe to see which companies asked this question
public class Solution
{
public static boolean isValid(String s)
{
char[] ch = s.toCharArray();
Stack<Character> stack = new Stack<>();
for (int i = 0; i < ch.length; i++)
{
if (stack.empty())
{
stack.push(ch[i]);
}
else
{
Character ch1 = stack.peek();
Character ch2 = ch[i];
if (ch1.equals('(') && ch2.equals(')') || ch1.equals('{') && ch2.equals('}')
|| ch1.equals('[') && ch2.equals(']'))
stack.pop();
else
stack.push(ch[i]);
}
}
if (stack.empty())
return true;
else
return false;
}
}
Valid Parentheses(java实现)Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.Sub