Leetcode(7) - valid parentheses

Given a string containing only  '(', ')', '{', '}', '[', ']' check whether the string is valid.

A valid string must satisfy:

  1. Opening parentheses must be closed with closing parentheses of the same type.
  2. Left parentheses must be closed in the correct order.

Note that empty strings are considered valid strings.

My own algorithm idea: first determine whether the string is empty, if it is empty, it is directly regarded as a valid string, and return true; then use the stack data structure to solve the problem, and judge the strings one by one, if it is a left bracket, put it on the stack , if it is a right parenthesis, judge whether the stack is empty, if it is empty, return false, and then judge whether the top of the stack is the corresponding left parenthesis, if so, pop the element at the top of the stack, if not, return false.

bool isValid(string s)
{
    if(s.empty()) return true;
    stack<char> sta;
    for(int i=0;i<s.size();i++)
    {
        if(s[i]=='(' || s[i]=='[' || s[i]=='{')
        {
            sta.push(s[i]);
        }
        else if(sta.empty())
        {
            return false;
        }
        else if((s[i] == ')' && sta.top()=='(') ||(s[i] == ']' && sta.top()=='[')||(s[i] == '}' && sta.top()=='{'))
        {
            get up();
        }
        else 
            return  false ;
    }
    if(sta.empty())
        return true;
    else
        return false;
}

Algorithm flaw: Because only the left parenthesis is entered each time, if the first one is the right parenthesis, it is necessary to first determine whether the stack is empty, otherwise, an error will occur when accessing the top element of the stack. This judgment is too much, not concise enough.

bool isValid(string s) {
        stack<char> result;  
        int n=s.size();  
        if(n==0) return true;  
     for(int i=0;i<n;i++)  
            {  
                if(result.empty())  
                    result.push(s[i]);  
                else if(result.top()=='('&&s[i]==')'||  
                      result.top()=='['&&s[i]==']'||  
                      result.top()=='{'&&s[i]=='}')   
                        result.pop();  
                else  
                    result.push(s[i]);  
                  
            }  
            return result.empty(); 
    }

As long as the element in the stack is empty, it is pushed to the stack, and when the top of the stack cannot be matched with the current element, it is also pushed to the stack, so as to avoid the right parenthesis at the beginning. Embarrassing, the rest of the ideas are the same as the above, and in the end, you only need to judge whether the stack is empty.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324977174&siteId=291194637