Given a string containing just the characters '(', ')', '{', '}', '[' and ']',
determine if the input string is valid.
The brackets must close in the correct order, "()" and "()[]{}" are
all valid but "(]" and "([)]" are
not.
最近想熟练用java,就先从字符串处理相关的题目开始做起。
用一个栈即可。
public static boolean isValid(String s) {
Stack<Character> stack = new Stack<Character>();
for(int i=0;i<s.length();i++){
char t = s.charAt(i);
if (t=='(' || t=='{' || t=='['){
stack.push(t);
}
else{
if (stack.empty())
return false;
char p = (char)stack.peek();
if ((p == '(' && t == ')' ) || (p == '[' && t == ']') || (p == '{' && t == '}')){
stack.pop();
}
else{
return false;
}
}
}
return stack.empty();
}
本文介绍如何使用Java实现括号匹配的有效性判断,通过栈数据结构来确保输入字符串中各种括号按照正确的顺序关闭。
1028

被折叠的 条评论
为什么被折叠?



