码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode(20)Valid Parentheses

时间:2015-08-09 17:11:15      阅读:102      评论:0      收藏:0      [点我收藏+]

标签:

题目

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.

分析

典型的括号匹配问题,数据结构一书中的典型实例。其程序实现,借助栈结构是最佳方法。

AC代码

class Solution {
public:
    bool isValid(string s) {
        int len = strlen(s.c_str());
        if (len == 0)
            return true;
        if (len % 2 != 0)
            return false;

        //括号匹配问题,用数据结构栈辅助实现
        stack<char> sta;
        for (int i = 0; i < len; i++)
        {
            if (s[i] != ‘)‘ && s[i] != ‘]‘ && s[i] != ‘}‘)
                sta.push(s[i]);
            else
            {
                if (sta.size() <= 0)
                    return false;
                if (s[i] == PairLetter(sta.top()))
                    sta.pop();
                else
                    return false;
            }//else
        }//for
        if (sta.size() == 0)
            return true;
        else
            return false;
    }

    char PairLetter(const char &c)
    {
        switch (c)
        {
        case ‘(‘:
            return ‘)‘; break;
        case ‘[‘:
            return ‘]‘; break;
        case ‘{‘:
            return ‘}‘; break;
        default:
            return 0; break;
        }
    }
};

GitHub测试程序源码

LeetCode(20)Valid Parentheses

标签:

原文地址:http://blog.csdn.net/fly_yr/article/details/47377335

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!