Is there a better way to write a java code for detecting valid parentheses in a String?

旧时模样 提交于 2020-07-09 11:56:08

问题


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

Problem statement:

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;
    }
    }

回答1:


You have simply not taken in consideration cases such as

()), where the stack can be empty when you receive a new closing paranthesis.

Simply add

!stk.isEmpty()&&

before each

stk.peek()

It's generally a good idea when working with vectors, matrix, etc. to verify if the element is within bounds and exists(or give internal reasoning as to why it isn't and why at least a check is necessary).

Also, sometimes you can have stuff such as

(, where the check doesn't meet a mismatching closing paranthesis to turn it into false. However, there is a mismatching opening paranthesis.

So the final part of the code has to be

    if(check == false || stk.empty() == false)

instead of &&, I put ||

I've run it on the site and it works :) .




回答2:


This code works on Leetcode. I've modified it so that instead of setting check to false, it just immediately returns false, since there's no point going through the whole string. It also checks if the stack is empty at each iteration. To avoid failing when the input starts with a closing parentheses, square bracket, or curly brace, it pushes the first character of the string onto the stack at the very start.

I've also improved it a bit by rejecting strings of odd lengths at the very start, which makes it run faster than 98.69% of all submissions to the Leetcode problem.

Stack<Character> stk = new Stack<Character>();
char temp;
int len = s.length();
if(len == 0) {
  return true;
} else if (len % 2 == 1) {
  return false;
}
stk.push(s.charAt(0));
for(int i = 1; i < len; i++) {
  temp = s.charAt(i);
  switch (temp) {
    case '{':
    case '(':
    case '[':
      stk.push(temp);
      break;
    case '}':
      if (stk.peek() == '{') {
        stk.pop();
        break;
      } else return false;
    case ')':
      if (stk.peek() == '(') {
        stk.pop();
        break;
      } else return false;
    case ']':
      if (stk.peek() == '[') {
        stk.pop();
        break;
      } else return false;
  }
  if (stk.isEmpty()) break;
}
return stk.isEmpty();

I hope you don't mind that I replaced your if-statements with a switch block. It's pretty much the same, but it looks clearer to me, at least. You can always change it back though, it'll work the same.




回答3:


This seems to work fine:

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
}


来源:https://stackoverflow.com/questions/62236025/is-there-a-better-way-to-write-a-java-code-for-detecting-valid-parentheses-in-a

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!