版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Naux1/article/details/89329090
给定一个只包括 '('
,')'
,'{'
,'}'
,'['
,']'
的字符串,判断字符串是否有效。
有效字符串需满足:
- 左括号必须用相同类型的右括号闭合。
- 左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
示例 1:
输入: "()" 输出: true
示例 2:
输入: "()[]{}" 输出: true
示例 3:
输入: "(]" 输出: false
示例 4:
输入: "([)]" 输出: false
示例 5:
输入: "{[]}" 输出: true
class Solution {
public boolean isValid(String s) {
Stack<String> staffs=new Stack<String>();
Stack<String> com=new Stack<String>();
int i;
if(s.length()%2!=0) //字符串长度为奇数时肯定不匹配
return false;
for(i=0;i<s.length();i++){
staffs.push(String.valueOf(s.charAt(i)));
}
while(!staffs.isEmpty()){
if(com.isEmpty())
com.push(staffs.pop());
String str=staffs.peek();
String str1=com.peek();
if((str.equals("(")&&str1.equals(")")) || (str.equals("[")&&str1.equals("]")) || (str.equals("{")&&str1.equals("}"))){
com.pop();
staffs.pop();
}
else{
com.push(str);
staffs.pop();
}
}
if(com.isEmpty())
return true;
return false;
}
}
利用两个栈来判断。