LeetCode #20. Valid Parentheses

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hh66__66hh/article/details/82533404

LeetCode #20. Valid Parentheses

题目描述

Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.

An input string is valid if:

1.Open brackets must be closed by the same type of brackets.
2.Open brackets must be closed in the correct order.

Note that an empty string is also considered valid.
Example 1:

Input: "()"
Output: true

Example 2:

Input: "()[]{}"
Output: true

Example 3:

Input: "(]"
Output: false

Example 4:

Input: "([)]"
Output: false

Example 5:

Input: "{[]}"
Output: true

思路

主要利用了栈的思想,并给( ){ } [ ] 这六个字符分别赋值为1、-1、2、-2、3、-3。从字符串的第一个字符开始往后遍历:
(1)如果遇到正数就压进栈里;
(2)如果出现负数,则看栈是否为空:
如果为空,则返回false;
如果不为空,则看栈顶数字是否为该数字的相反数,如果不是则返回false,如果是则将栈顶元素抛出,接着看字符串中的下一个字符。

这里要注意:
1.如果字符串的第一个字符对应的数字为负数,则可以直接返回false;
2.当字符串遍历完以后,如果栈不为空,则返回false,为空才返回true。

代码

class Solution {
public:
    bool isValid(string s) {
        stack<int>ss;
        map<char,int>m;
        m.clear();
        m['('] = 1;
        m[')'] = -1;
        m['{'] = 2;
        m['}'] = -2;
        m['['] = 3;
        m[']'] = -3;
        while(!ss.empty()) {
            ss.pop();
        }
        int i, j;
        if(m[s[0]]<0) {
            return false;
        }
        for(i=0; i<s.length(); i++) {
            j = m[s[i]];
            if(j>0) {
                ss.push(j);
            }
            else {
                if(ss.empty()) {
                    return false;
                }
                if(-1*j != ss.top()) {
                    return false;
                }
                else {
                    ss.pop();
                }
            }
        }
        if(ss.empty()) {
            return true;
        }
        return false;


    }
};

猜你喜欢

转载自blog.csdn.net/hh66__66hh/article/details/82533404