20. Valid Parentheses题目和答案详解

1 题目简述

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

给定一个包含只字符'('')''{''}''['  ']'的字符串,确定输入字符串是否有效。

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

括号必须以正确的顺序关闭, "()"  "()[]{}"是有效的,但"(]"  "([)]"是无效的。

2 答案详解

(1) 解决思想

  本次解答采用C++编写,C++相对于C语言的一个重要的特点是:面向对象编程(OOP),故我们采用类的方法来实现所述要求。

  我们知道输入的字符串三种类型的括弧只有在少数几种情况下有效,其他情况均为无效,即字符'('的下一个字符为')',  '{'的下一个字符为'}''['  的下一个字符为 ']',且不存在落单的括弧时,该字符串有效。字符串无效的情况有很多,包括:存在除括弧的别的字符,字符串为空,存在未配对的括弧等。

  对于配对的括弧,可以采用栈stack来解决。遍历字符串,当遇见'(''{''['其中之一时入栈,先判断栈是否为空,不为空则返回false,为空则将其入栈;之后遇见配对的括弧后出栈;若遇见别的字符且栈为空,则直接范围false;最后遍历完字符串后,若栈为空则返回true,不为空则返回false

(2) 设计程序

  所设计的程序采用类模板,程序如下:

#include <iostream>
#include <string>
#include <stack>

using std::cout;
using std::endl;
using std::string;
using std::stack;
using std::boolalpha;
using std::noboolalpha;

template<class T>
class Solution
{
private:
    T str_;
public:
    Solution(const T& str):str_(str) {}
    bool isValid();
};

template<class T>
bool Solution<T>::isValid()
{
    if(str_.size() == 0) {
        return false;
    }
    stack<char> st;
    for(int i = 0; i < str_.size(); i++) {
        if( st.empty() and (str_[i]=='{' or str_[i]=='[' or str_[i]=='(') ) {
            st.push(str_[i]);
        } else if( str_[i]=='}' and st.top()=='{') {
            st.pop();
        } else if( str_[i]==']' and st.top()=='[') {
            st.pop();
        } else if( str_[i]==')' and st.top()=='(') {
            st.pop();
        } else {
            return false;
        }
    }
    return st.empty();
}

int main()
{
    string str="[](}){}";
    cout << "The string is:" << str << endl;
    Solution<string> sol(str);
    cout << "It is Valid? ------";
    cout << boolalpha << sol.isValid() << noboolalpha << endl;
}
程序运行结果为:

The string is:[](}){}
It is Valid? ------false



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值