20-Valid Parentheses

题目描述

 

思路比较简单,就是栈的应用

但有几个坑点:

1. 在判断过程中,获取栈top元素时,需要先判断是否为空

2. 结束返回时,注意判断是不是遍历了整个string(以防类似于这种情况"{}]]")

class Solution {
public:
   bool isValid(string s) {
        std::stack<char> leftParenthese;
        char tmpChar = 0;
       int index = 0;
        for (index = 0; index < s.length(); ++index) {
            tmpChar = s.at(index);
            if ('(' == tmpChar || '{' == tmpChar || '[' == tmpChar) {
                leftParenthese.push(tmpChar);
            } else if (')' == tmpChar) {
                if (leftParenthese.empty() || '(' != leftParenthese.top())
                    break;
                else 
                    leftParenthese.pop();
            } else if ('}' == tmpChar) {
                if (leftParenthese.empty() || '{' != leftParenthese.top())
                    break;
                else 
                    leftParenthese.pop();
            } else if (']' == tmpChar) {
                if (leftParenthese.empty() || '[' != leftParenthese.top())
                    break;
                else 
                    leftParenthese.pop();
            }
        }
        return leftParenthese.empty() && index == s.length();
    }
};

优化点:

1. 那么多if看着闹心,switch中break又不能直接跳出for循环

2. map又大材小用

3. for循环中使用s.length()太耗时!!!!(从4ms到0ms,100%,内存是8.4M,96.12%)

class Solution {
public:
   bool isValid(string s) {
        std::stack<char> leftParenthese;
        char tmpChar = 0;
       char tmpArray[256] = {0};
       tmpArray[')'] = '(';
       tmpArray[']'] = '[';
       tmpArray['}'] = '{';
       int index = 0;
       int sLength = s.length();
        for (index = 0; index < sLength; ++index) {
            tmpChar = s.at(index);
            if ('(' == tmpChar || '{' == tmpChar || '[' == tmpChar) {
                leftParenthese.push(tmpChar);
            } else if (leftParenthese.empty()) {
                break;
            } else if (tmpArray[tmpChar] != leftParenthese.top()){
                break;
            } else {
                leftParenthese.pop();
            }
        }
        return leftParenthese.empty() && index == sLength;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值