做括号匹配,一开始想到的肯定就是最直接的办法,使用栈:
使用栈的时候一定要注意,考虑 栈会不会在运行时为空
public class Solution {
public boolean isValid(String s) {
Stack<Character> ps = new Stack<Character>();
int size = s.length();
ps.push(s.charAt(0));
for(int i=1; i<size;i++){
if( !ps.empty() && isP(ps.peek(),s.charAt(i))){ // 同时要考虑当stack为空的时候,就没的比较了
ps.pop();
} else {
ps.push(s.charAt(i));
}
}
return ps.empty();
}
public boolean isP(Character a,Character b){
if(a == '(' && b == ')') return true;
if(a == '{' && b == '}') return true;
if(a == '[' && b == ']') return true;
return false;
}
}
大神的算法,更为直接,beat97%:
public class Solution {
public boolean isValid(String s) {
boolean isNot = true;
int j=0;
// 以下代码可以看出作者非常注意考虑 边际效果
if(s.length()%2!=0||s.length()==0||s.charAt(0)==')'||s.charAt(0)=='}'||s.charAt(0)==']'){
return false;
}
char[] point=new char[s.length()];
for(int i=0;i<s.length();i++){
if(s.charAt(i)=='('||s.charAt(i)=='{'||s.charAt(i)=='[')
{
point[j]=s.charAt(i);
j++;
} else {
if(point[j-1]=='('&&s.charAt(i)==')'||point[j-1]=='{'&&s.charAt(i)=='}'||point[j-1]=='['&&s.charAt(i)==']')
{
j--;
} else {
return false;
}
}
}
if(j>0){
return false;
}
return isNot;
}
}
思路是用 j的下标来标记回退的位置,思想是和栈是一样的