LeetCode【#20】Valid Parentheses 【用字符数组模拟栈】

题目链接:

点击跳转

 

题目:

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

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.

Note that an empty string is also considered valid.

Example 1:

Input: "()"
Output: true

Example 2:

Input: "()[]{}"
Output: true

Example 3:

Input: "(]"
Output: false

Example 4:

Input: "([)]"
Output: false

Example 5:

Input: "{[]}"
Output: true


题目分析:

给定一组字符串,判断是不是有效的括号。

 

解题思路:

多开一个字符数组 temp,存储还没有匹配的括号。只要括号没有匹配,就放进这个数组里,如果下一个括号和该字符数组的最后一位进行了匹配,那么字符数组的最后一位去掉(相当于下标向前移动一位)。最后只要判断,是不是这个下标小于0,如果小于0,则说明是有效的true。

例子:{[]},先将第0位存进去 {,temp 的下标 ind = 0

然后开始从原字符串的第 1 位开始,发现是 [,所以继续存进 temp 里,ind = 1。

当第 2 位时,是 ] ,则判断 temp 的最后一位是 [,可以匹配,所以temp 的下标向前一位,ind = 0;

到第 3 位时,时 },判断temp 的最后一位是 {,可以匹配,所以temp 的下标向前一位,ind  = -1。

退出循环,判断 ind 是否小于 0,是,所以是有效的括号。

其中有一个问题,假如在循环过程中,ind就小于0了,那么就相当于 temp里没存放,那么此时,无论原字符串的下一位是什么,都直接存放进 temp,保证temp里有可以判断比较的。

 

而在题目说到,空的字符串也是有效的,所以我们一开始判断原字符串的长度,如果==0,说明返回true 。

而且因为要匹配,所以如果长度不是偶数的话,那一定不是有效的。

 

AC代码:

class Solution {
public:
    bool isValid(string s) {
        
        int len = s.length();
        if(len==0)
            return true;
        if(len%2 != 0)
            return false;
        int index = 0;
        char temp[len+10];
        temp[index] = s[0];
        for(int i = 1;i < len;i++)
        {
            if(index < 0)
            {
                index = 0;
                temp[0] = s[i];
                continue;
            }
            if(s[i]==')' && temp[index]=='(')
            {
                --index;
                continue;
            }
            if(s[i]==']' && temp[index]=='[')
            {
                --index;
                continue;
            }
            if(s[i]=='}' && temp[index]=='{')
            {
                --index;
                continue;
            }
            temp[++index] = s[i];
            
        }
        if(index < 0)
            return true;
        else
            return false;
    }
};

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值