问题链接
问题描述
判断给出的字符串中的括号是否合法。
解决办法
public class Solution {
public boolean isValid(String s) {
List<String> parenthesisList = new ArrayList();
for(int i = 0;i < s.length();i ++){
char c = s.charAt(i);
if(isLeftParenthesis(c)){
parenthesisList.add(String.valueOf(c));
}
else if(isRightParenthesis(c)){
if(parenthesisList.size()==0){
return false;
}
int lastPosition = parenthesisList.size() - 1;
String lastParenthesis = parenthesisList.get(lastPosition);
if(!isParenthesesMatch(lastParenthesis.charAt(0),c)){
return false;
}
parenthesisList.remove(lastPosition);
}
}
return parenthesisList.size() == 0;
}
public static boolean isParenthesesMatch(char left,char right){
if(left == '{' && right == '}'){
return true;
}
if(left == '(' && right == ')'){
return true;
}
if(left == '[' && right == ']'){
return true;
}
return false;
}
public static boolean isLeftParenthesis(char c){
switch(c){
case '{':
case '(':
case '[':
return true;
default:
return false;
}
}
public static boolean isRightParenthesis(char c){
switch(c){
case '}':
case ')':
case ']':
return true;
default:
return false;
}
}
public static boolean isParenthesis(char c){
return isLeftParenthesis(c) || isRightParenthesis(c);
}
}