有没有更好的方法来编写 Java 代码来检测字符串中的有效括号? [英] Is there a better way to write a java code for detecting valid parentheses in a String?
问题描述
我试图解决 leetcode 中的一个问题,但我无法通过所有测试用例.我尝试使用堆栈.每当有一个左括号时,我就把它压入堆栈,每当有一个右括号时,我检查并弹出堆栈顶部是否存在正确的左括号.我在最后检查堆栈是否为空
I tried to solve a problem in leetcode and im not able to pass all the test cases. I tried to use stack. Whenever there is an open parenthesis, I push it into the stack and whenever there is a close parentheses, I check and pop if the correct open parenthesis is present on the top of the stack. I check if the stack is empty in the last
给定一个只包含字符 '(', ')', '{', '}', '[' and ']', 确定输入字符串有效.
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
输入字符串在以下情况下有效:
An input string is valid if:
左括号必须由相同类型的括号封闭.
开放括号必须以正确的顺序关闭.
请注意,一个空的字符串也被认为是有效的.
Open brackets must be closed by the same type of brackets.
Open
brackets must be closed in the correct order.
Note that an empty
string is also considered valid.
Stack<Character> stk = new Stack<Character>();
boolean check = true;
char temp;
if(s.length() == 1)
{
return false;
}
else if(s.length() == 0)
{
return true;
}
else
{
for(int i = 0 ; i < s.length() ; i++)
{
temp = s.charAt(i);
if(temp == '{' || temp == '(' || temp == '[')
{
stk.push(temp);
}
else if(temp == '}')
{
if(stk.peek() == '{')
{
stk.pop();
}
else
{
check = false;
}
}
else if(temp == ')')
{
if(stk.peek() == '(')
{
stk.pop();
}
else
{
check = false;
}
}
else if(temp == ']')
{
if(stk.peek() == '[')
{
stk.pop();
}
else
{
check = false;
}
}
}
if(check == false && stk.empty() == false)
{
return false;
}
else
{
return true;
}
}
推荐答案
这似乎工作正常:
public boolean isValid(String s) {
int n = s.length();
if (n == 0) return true;
if (n % 2 == 1) return false;
Stack<Character> st = new Stack<>();
for (char c : s.toCharArray()) {
if (c == '{' || c == '[' || c == '(') {
st.push(c);
} else if (st.isEmpty()) { // no opening bracket stored
return false;
} else {
char prev = st.pop();
switch(c) { // matching open and close bracket
case '}': if (prev != '{') return false; else break;
case ']': if (prev != '[') return false; else break;
case ')': if (prev != '(') return false; else break;
}
}
}
return st.isEmpty(); // stack must be empty in the end - all pairs matched
}
这篇关于有没有更好的方法来编写 Java 代码来检测字符串中的有效括号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!