leetcode020 Valid Parentheses

35 篇文章 0 订阅
35 篇文章 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.

思路:

这道题要做出来可以说非常简单,数据结构课程在讲栈的这节时有例题就是这个。我开始想用JAVA集合框架中的类来做,但一思考,对于本题来说集合框架太大材小用了。如果自己实现栈也可以,但还是不够高效。于是,我用了一个和字符串等长的数组来实现栈的结构。只需要一个指向数组末端的指针即可。具体实现看代码。

代码:

public boolean isValid(String s)
{
    if(s == null || s.length() == 0)
        return true;
    char[] sChars = s.toCharArray();
    char[] stack = new char[sChars.length];
    int top = 0;
    boolean res = true;
    for(char c : sChars)
    {
        if(c == '(' || c == '{' || c == '[')
        {
            stack[top++] = c;
            continue;
        }
        char tmp = top!=0? stack[--top]:'\0';
        if(c == ')')
        {
            if(tmp != '(')
            {
                res = false;
                break;
            }
        } else if(c == ']')
        {
            if(tmp != '[')
            {
                res = false;
                break;
            }
        } else if(c == '}')
        {
            if(tmp != '{')
            {
                res = false;
                break;
            }
        }
    }
    return top == 0 && res;
}

结果细节(图):

image

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值