[LeetCode] 20. 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.

解法一: stack

 1 class Solution {
 2 public:
 3     bool isValid(string s) {
 4         unordered_set<char> left = {'(', '[', '{' };
 5         unordered_set<char> right = {')', ']', '}' };
 6         unordered_map<char, char> ht = {{'(',')'}, {'[', ']'}, {'{','}'} };
 7         stack<char> stk;
 8         bool ret = false;
 9         
10         for (int i = 0; i < s.size(); i++){
11             if (left.count(s[i])){
12                 stk.push(s[i]);
13             }else if(right.count(s[i])){
14                 // check empty !!
15                 if (!stk.empty() && ht[stk.top()] == s[i]){
16                     stk.pop();
17                 }else{
18                     return false;
19                 }
20             }else{
21                 return false;
22             }
23         }
24         
25         return stk.empty();
26     }
27 };

 

博主在Linked-in面试中碰到过这題的简化版: 一个字符串只包含小括号 '(' 或者')', 检查括号匹配是否正确. 

该简化版的解法, 可以直接用一个计数器, 而不需要堆栈:

bool matched(String s){
    int left = 0;
        
    for (int i = 0; i < s.size(); i++){
        if (s[i] == '('){
            left++;
            continue;
        }else if (s[i] == ')'){
            if (left > 0){
                left--;
            }else{
                return false;
            } 
        }
    }
    
    return left == 0;
 }

 

转载于:https://www.cnblogs.com/amadis/p/5926534.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值