给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
示例 1:
输入: "()"
输出: true
示例 2:
输入: "()[]{}"
输出: true
示例 3:
输入: "(]"
输出: false
示例 4:
输入: "([)]"
输出: false
示例 5:
输入: "{[]}"
输出: true
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-parentheses
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
import java.util.Stack;
public class 有效的括号 {
/*
* 有效字符串要求:
* 1.左括号必须用相同类型的右括号闭合
* 2.左括号必须以正确的顺序闭合
*/
public static boolean ifInPairs(Character a,char b){
boolean result=false;
switch(b){
case ')':
if(a.equals('(')){
result=true;
}
break;
case ']':
if(a.equals('[')){
result=true;
}
break;
case '}':
if(a.equals('{')){
result=true;
}
break;
}
return result;
}
/**
* 利用java中自带栈对象,判断输入字符串是否是有效字符串
* @param s 所要判断的字符串
* @return 是否是有效字符串
*/
public static boolean isValid(String s) {
boolean result=false;
/**
* 1. 首先将字符串s转换成字符数组
* 2. 循环遍历字符数组 入栈 判断
*/
if(s.isEmpty()){
result=true;
}else{
char t[]=s.toCharArray();
Stack<Character> stackForS=new Stack<Character>();
stackForS.push(new Character(t[0]));
for(int i=1;i<s.length();i++){
if(stackForS.empty()||!ifInPairs(stackForS.peek(),t[i])){//判断是否与栈顶元素相等
stackForS.push(new Character(t[i]));//不相等则
}else{
stackForS.pop();//相等则出栈
}
}
if(stackForS.empty()){
result=true;
}
System.out.println("测试输出");
for (Character x : stackForS) {
System.out.println(x);
}
}
return result;
}
public static void main(String args[]){
// String s="[]{()()}";
// String s="[{()()}";
// String s="[]}";
String s="";
System.out.println(isValid(s));
}
}