LeetCode 之 Valid Parentheses — C++ 实现

来源:互联网 发布:qq飞车鬼战刀数据 编辑:程序博客网 时间:2024/05/17 22:48

Valid Parentheses

 

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.

给定一个只包含 '('')''{''}''[' 和']' 的字符串,验证字符串是否有效。

括号必须以正确的顺序关闭,如 "()" 和 "()[]{}" 合法,"(]""([)]" 不合法。

分析:

使用堆栈,遇到左括号入栈,遇到右括号出栈,若和右括号匹配则继续比较,否则不合法;如果比较完后堆栈中还剩下未匹配的括号,说明存在左括号没有闭合,也不合法。


class Solution {public:    bool isValid(string s) {        stack<char> hasNotMatch;        int index = 0;        int strLen = s.length();                if(s.empty()) //空字符串,匹配            return true;                    for(; index < strLen; ++index)        {            switch(s[index])            {                //左括号直接压栈,不用比较                case '(':                case '[':                case '{':                {                    hasNotMatch.push(s[index]);                }                break;                //每出现一个右括号,匹配一次                case ')':                {                    if(hasNotMatch.empty()) //栈空,没有待匹配德左括号                        return false;                    if(hasNotMatch.top() == '(')//匹配,出栈                    {                        hasNotMatch.pop();                    }                    else                        return false;                }                break;                case ']':                {                    if(hasNotMatch.empty())                        return false;                    if(hasNotMatch.top() == '[')//匹配,出栈                    {                        hasNotMatch.pop();                    }                    else                        return false;                }                break;                case '}':                {                    if(hasNotMatch.empty())                        return false;                    if(hasNotMatch.top() == '{')//匹配,出栈                    {                        hasNotMatch.pop();                    }                    else                        return false;                }                break;                default:                break;            }        }        if(!hasNotMatch.empty())//栈中剩有不匹配的左括号        {            return false;        }                return true;    }};

0 0
原创粉丝点击