'(', ')', '{', '}', '[' and ']', determine if the input string is valid.The brackets must close in the correct order,
"()" and "()[]{}" are all valid but "(]" and "([)]" are not.Solution:
public class Solution {
public boolean isValid(String s) {
ArrayDeque<Character> stack = new ArrayDeque<Character>();
for (int i=0; i<s.length(); i++)
{
if(s.charAt(i)=='(' || s.charAt(i)=='[' || s.charAt(i)=='{')
stack.push(s.charAt(i));
else
{
if(stack.isEmpty())
return false;
char lastOpenParenthesis = stack.pop();
if((s.charAt(i)==')' && lastOpenParenthesis!= '(') || (s.charAt(i)==']' && lastOpenParenthesis!= '[') ||
(s.charAt(i)=='}' && lastOpenParenthesis!= '{'))
return false;
}
}
return stack.isEmpty();
}
}
No comments :
Post a Comment