算法作业HW14:Leetcode20 Valid Parentheses

Description:

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

Note:

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

Solution:

  Analysis and Thinking:

题目要去对于输入的字符串,其中包含‘{‘ ’}’、‘(‘ ’)’等闭合字符,判断字符串是否合法。合法的标准当然是要以正确的顺序闭合。这是一个明显的栈应用问题,利用stack就可以解决,例如遇到左闭合符号入栈,如果遇到了一个右闭合符号,弹出一个左闭合符号,看是否匹配,因为闭合符号遵循最近匹配原则,因此扫描一遍字符串,就可以得出结果。


  Steps:

1.遍历字符串中每一个字符

2.若当前字符与栈顶匹配,则出栈

3.否则,将当前遍历元素入栈


Codes:

class Solution {  
public:  
    bool isValid(string s) {  
        if(s.length() == 0)  //空字符串,合法
        {  
            return true;  
        }  
  
        stack<char> record; //用于记录字符串的栈
        record.push(s[0]);    
        
        for(int i = 2; i < s.length(); i++)  
        {  
            if(!record.empty() && isValid_helper(record.top(), s[i]))  //判断是否有闭合符号匹配,若有,则出栈,否则将字符入栈  
            {  
                record.pop();  
            }  
            else  
            {  
                record.push(s[i]);  
            }  
        }  
  
        if(record.empty())  //判断的标准就是,是否所有的闭合符号都被匹配  
        {  
            return true;  
        }  
        else  
        {  
            return false;  
        }  
    }  
  
    bool isValid_helper(char a, char b) //用于辅助判断闭合符号是否匹配  
    {  
        switch(a)
        {
        case '(':
            if (b==')')
                return true;
            break;
        case '{':
            if (b=='}')
                return true;
            break;
        case '[':
            if (b==']')
                return true;
            break;
        default:
            return false;
        }
    }
       
};  


Results:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值