(70)20. Valid parentheses (leetcode)

题目链接:
https://leetcode-cn.com/problems/valid-parentheses/
难度:简单
20. 有效的括号
	给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。

有效字符串需满足:
	左括号必须用相同类型的右括号闭合。
	左括号必须以正确的顺序闭合。
	注意空字符串可被认为是有效字符串。

It really is a simple question. . . . . . (This is useless unordered_map)

class Solution {
    
    
public:
    bool isValid(string s) {
    
    
        int n=s.size();
        if(!n){
    
    
            return true;
        }
        stack<char> sta;
        for(int i=0;i<n;++i){
    
    
            char y=s.at(i);
            if(y=='('||y=='['||y=='{'){
    
    
                sta.push(y);
            }else{
    
    
                if(sta.empty()){
    
    
                    return false;
                }
                char x=sta.top();
                sta.pop();
                if((x=='('&&y==')')||(x=='['&&y==']')||(x=='{'&&y=='}')){
    
    
                    continue;
                }
                return false;
            }
        }
        if(sta.empty()){
    
    
            return true;
        }
        return false;
    }
};

Use unordered_map

class Solution {
    
    
public:
    bool isValid(string s) {
    
    
        int n=s.size();
        if(!n){
    
    
            return true;
        }else if(n%2){
    
    
            return false;
        }
        unordered_map<char,char> vmap={
    
    
            {
    
    ')','('},
            {
    
    '}','{'},
            {
    
    ']','['}
        };
        stack<char> sta;
        for(int i=0;i<n;++i){
    
    
            char x=s.at(i);
            if(vmap.find(x)!=vmap.end()){
    
    
                if(sta.empty()||sta.top()!=vmap[x]){
    
    
                    return false;
                }
                sta.pop();
            }else{
    
    
                sta.push(x);
            }
        }
        return sta.empty();
    }
};

Guess you like

Origin blog.csdn.net/li_qw_er/article/details/107994932