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.
Solution:O(n)
public class Solution {
public boolean isValid(String s) {
Stack<String> stack = new Stack<String>();
for(int i=0; i<s.length();i++){
String str = ""+s.charAt(i);
if(str.equals("(") || str.equals("{")|| str.equals("["))
stack.push(str);
else{
if(stack.isEmpty())
return false;
String popup = stack.pop();
if(str.equals(")") && popup.equals("(") )
continue;
if(str.equals("]") && popup.equals("[") )
continue;
if(str.equals("}") && popup.equals("{") )
continue;
return false;
}
}
return stack.isEmpty();
}
}
Key Concept: Use stack to help make decision
沒有留言:
張貼留言