这个是一个很明显的栈结构问题,只要是左括号执行入栈,右括号的话检测栈顶字符是否与之匹配,匹配执行出栈操作。
class Solution {
public boolean isValid(String s) {
if(s.equals(""))return true;
if(s==null)return false;
char[] c = s.toCharArray();
char[] n = new char[c.length];
n[0] = c[0];
int index = 0;
for(int i=1;i<c.length;i++){
if(index!=-1&&n[index]==getChar(c[i]))
index--;
else{
if(chackChar(c[i]))return false;
n[++index]=c[i];
}
}
return index==-1;
}
public static boolean chackChar(char c){
if(c==')'||c==']'||c=='}') return true;
else return false;
}
public static char getChar(char c){
switch(c){
case '(':
return ')';
case ')':
return '(';
case '[':
return ']';
case ']':
return '[';
case '{':
return '}';
case '}':
return '{';
default : return c;
}
}
}
题目来源:leetcode