- 用栈
- stk.peek()顶点
- Character
import java.util.*;
public class Solution {
/**
*
* @param s string字符串
* @return bool布尔型
*/
public boolean isValid (String s) {
// write code here
Stack<Character> stk = new Stack<Character>();
for(int i=0;i<s.length();i++){
switch(s.charAt(i)){
case '(':
case '[':
case '{':
stk.push(s.charAt(i)); //当前字符为'(','{','['时,元素入栈
break;
case ')':
if(stk.empty() || stk.peek() != '(') //栈空或者括号栈顶字符与当前字符不匹配,则序列为不合法序列
return false;
stk.pop(); //匹配的栈顶元素出栈
break;
case ']':
if(stk.empty() || stk.peek() != '[')
return false;
stk.pop();
break;
case '}':
if(stk.empty() || stk.peek() != '{')
return false;
stk.pop();
break;
}
}
return stk.empty()?true:false; //当括号以正确顺序关闭时则最后的栈为空
}
}