[LeetCode] Valid Parentheses

前言

Valid Parentheses是Leetcode的一道基础题,考察括号匹配算法,使用栈结构。

题目

题目描述

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.

题目分析

括号匹配的思路比较简单,检测输入字符串中的字符,若是左括号就入栈,若是右括号,就pop一个元素表示与其配对,配对成功则继续访问下一个字符,否则退出。出现非括号字符则跳过。

代码

class Solution {
public:
  bool isValid(string s) {
    string left = "([{";
    string right = ")]}";
    stack<char> stk;
    for (int i = 0; i < s.size(); i++) {
      if (left.find(s[i]) != string::npos) {
        stk.push(s[i]);
      } else {
        if (stk.empty() || stk.top() != left[right.find(s[i])])
          return false;
        else
          stk.pop();
      }
    }    
    return stk.empty();
  }
};

在这里说明几点:

  • string类型的find()函数将返回字符(即find的参数)在该串中的位置索引,若未找到(即无该字符)返回string::npos
  • 主循环中的i还可用自动指针(auto pointer)实现,如下:
for (auto atp : s) {
  if (left.find(atp) != string::npos) {
    stk.push(atp);
    } else {
      if (stk.empty() || stk.top() != left[right.find(atp)])
        return false;
      else
        stk.pop();
    }
}    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值