leetcode题目例题解析(十六)

本文介绍了一个LeetCode上的经典算法题目——括号匹配验证的有效解法。通过使用栈的数据结构,可以高效地判断输入字符串中括号是否正确配对。文章详细解析了实现代码,并提供了完整的解决方案。

leetcode题目例题解析(十六)

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.

题意解析:

判断一个括号的序列是否满足合法的序列,每一对括号内部都只能有完整的括号对

解题思路:

利用栈的思想来做

代码:

class Solution {
public:
  bool isValid(string s) {
    char stack[10000];
    int top = -1;
    int length = s.length();
    for (int i = 0; i < length; i++) {
      if (top == -1) {
    stack[++top] = s[i];
      } else {
    if (stack[top] == '('&&s[i] == ')')
      top--;
    else if (stack[top] == '{'&&s[i] == '}')
      top--;
    else if (stack[top] == '['&&s[i] == ']')
      top--;
    else
      stack[++top] = s[i];

      }
    }
    if (top == -1)
      return true;
    else
      return false;
  }
};

原题目链接:
https://leetcode.com/problems/valid-parentheses/description/

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值