zoukankan      html  css  js  c++  java
  • leetcode: Valid Parentheses

    http://oj.leetcode.com/problems/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.

    思路

    用一个堆栈保存左括号然后匹配即可。

     1 class Solution {
     2 public:
     3     bool isValid(string s) {
     4         stack<char> left_pars;
     5         const char *p = s.c_str();
     6         
     7         while (*p != '') {
     8             if (('(' == *p) || ('[' == *p) || ('{' == *p)) {
     9                 left_pars.push(*p);
    10             }
    11             else {
    12                 if (left_pars.empty()) {
    13                     return false;
    14                 }
    15                 
    16                 char exp_left_par;
    17                 
    18                 if (')' == *p) {
    19                     exp_left_par = '(';
    20                 }
    21                 else if (']' == *p) {
    22                     exp_left_par = '[';
    23                 }
    24                 else {
    25                     exp_left_par = '{';
    26                 }
    27                 
    28                 if (left_pars.top() == exp_left_par) {
    29                     left_pars.pop();
    30                 }
    31                 else {
    32                     return false;
    33                 }
    34             }
    35             
    36             ++p;
    37         }
    38         
    39         return left_pars.empty() ? true : false;
    40     }
    41 };
  • 相关阅读:
    Celery(异步任务,定时任务,周期任务)
    SQLAlchemy的应用创建
    SQLAlchemy多对多
    SQLAlchemy
    app开发-2
    app开发-3
    app开发-1
    MongoDB-pymongo
    MongoDB-增删改查
    MongoDB-数据类型
  • 原文地址:https://www.cnblogs.com/panda_lin/p/valid_parentheses.html
Copyright © 2011-2022 走看看