LeetCodeOJ. Valid Parentheses, validparentheses

Source: Internet
Author: User

LeetCodeOJ. Valid Parentheses, validparentheses

For questions, see: Https://oj.leetcode.com/problems/valid-parentheses/

Topic Overview

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"(]"And"([)]"Are not.

Solutions

A typical example of data structure. When we read the brackets on the left (including'(','['And'{'), And press into the stack. when reading the parentheses on the right, compare the elements at the top of the stack. If they do not match, the parentheses in the expression cannot be paired.

Problems encountered

[][Status
When the string is read, the elements in the stack may not be empty, and the brackets cannot be completely matched.

[]]Status
When read to 2nd]We will callstack.top()Function. However, the stack is empty, so a Segment Fault exception occurs.

Source code
class Solution {public:    bool isValid(std::string s) {        for ( auto itr = s.begin(); itr != s.end(); ++ itr ) {            if ( *itr == '(' || *itr == '[' || *itr == '{' ) {                st.push(*itr);            } else if ( *itr == ')' || *itr == ']' || *itr == '}' ) {                if ( st.empty() ) {                    return false;                }                char topChar = st.top();                if ( *itr == ')' && topChar != '(' ) {                    return false;                } else if ( *itr == ']' && topChar != '[' ) {                    return false;                } else if ( *itr == '}' && topChar != '{' ) {                    return false;                }                st.pop();            }        }        if ( st.empty() ) {            return true;        } else {            return false;                    }    }private:    std::stack<char> st;};

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.