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.
JAVA
直接使用栈来做,不过之前在看书的时候,好像说java中的栈被取代了???记不清了,这次先用栈做一下,下次去书中找一下看看是不是自己记错了。时间复杂度
O(N)
效率排名在中间,可以考虑优化一下。
public class Solution {
public boolean isValid(String s) {
if(s.length() % 2 != 0){
return false;
}
Stack<Character> sta = new Stack<Character>();
char temp;
for(int i = 0; i < s.length();++i){
temp = s.charAt(i);
if(sta.empty()){
sta.push(temp);
}else {
switch (temp){
case '(':
case '[':
case '{':
sta.push(temp);
break;
case ')':
if(sta.peek() == '('){
sta.pop();
}else{
return false;
}
break;
case ']':
if(sta.peek() == '['){
sta.pop();
}else{
return false;
}
break;
case '}':
if(sta.peek() == '{'){
sta.pop();
}else{
return false;
}
break;
}
}
}
if(sta.empty()){
return true;
}
return false;
}
}