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 boolean isValid(String s) {
int len = s.length();
if(0 == len)
return true;
// can not use char in template
// Use queue instead of stack at first ........, can't find the bug even.
Stack pq = new Stack();
/*
pq.peek() == new Character('[')
OK.
pq.peek() == '['
'[' == pq.peek()
null return can not compare with primitive char
null pointer execption
*/
for(int i = 0; i < len; ++i){
char c = s.charAt(i);
if(c =='(' || c =='{' || c =='['){
pq.push(c);
// The peek operation is different from queue to stack. We can peek empty queue, but not for stack.
}else if(pq.empty()){
return false;
}else{
if(c == ')')
// use poll instead of peek here first, not working for input "]", empty queue, must peek before poll
if(pq.peek().charValue() == '(') pq.pop(); else return false;
if(c == '}')
if(pq.peek().charValue() == '{') pq.pop(); else return false;
if(c == ']')
if(pq.peek().charValue() == '[') pq.pop(); else return false;
}
}
// shouldn't return true here. pq must be empty
return pq.empty();
}
}
No comments:
Post a Comment